Polymer- using custom element in other projects like angular and Java jsp - polymer

I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java
my-element.js:
class MyElement extends HTMLElement {
// This gets called when the HTML parser sees your tag
constructor() {
super(); // always call super() first in the ctor.
this.msg = 'Hello, World!';
}
// Called when your element is inserted in the DOM or
// immediately after the constructor if it’s already in the DOM
connectedCallback() {
this.innerHTML = `<form action="/action_page.php">
<div class="container">
<label><b>Name</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Age</b></label>
<input type="text" placeholder="Enter Age" name="age" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Add</button>
</div>
</div>
</form>`;
}
}
// This registers your new tag and associates it with your class
window.customElements.define('my-element', MyElement);
my-element.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">
<script src="my-element.js"></script>
<!-- <link rel="import" href="add-form.html"> -->
</head>
<body>
<my-element></my-element>
</body>
</html>
Two issues I am struggling with now are below
1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?
<link rel="import" href="my-element.html">
<script src="my-element.js"></script>
<my-element></my-element>
I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements
[
{
"name":"Name",
"type":"text",
"size":"20",
"readyOnly": false,
"validateFunction":"onlyText"
},
{
"name":"Age",
"type":"number",
"size":"3",
"readyOnly": false,
"validateFunction":"onlyNumber"
}
]
I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors
<my-element form-data="{{data}}"></my-element>

ad 1) yes you can use your element with every server system you would like. It's "just html" that the beauty in it :)
ad 2)
HTMLElement won't do anything automatically. So if you wish to access your json you will have to do something like this
<my-element form-data="{'name': 'Name', 'type': 'text'}""></my-element>
connectedCallback() {
let rawData = this.getAttribute('form-data');
let jsonData = JSON.parse(rawData.replace(/'/g, '"'));
}
Notice that in the form-data json there are ' instead of ". So we have to replace them before using JSON.parse.

it looks like this is using a web component as opposed to a polymer component. The native web component API does not include data binding, although angular and polymer both do (but implemented in different ways).
Native web components and polymer components can be used with Angular as well as other frameworks.
Depending on whether you are using Angular.js(1) or Angular(2+), setting up the data object to be passed into the DOM will vary, but in general the data should be "set up" so to speak in the JS and passed into the DOM. Otherwise as #daKmoR said, the data would need to be declared as he did in his example.
There are packages that assist in implementing data 2-way binding between polymer's data bindings and angulars bindings if that is needed.
Trey

Related

How to use Custom Elements with template? [duplicate]

This question already has an answer here:
Nested element (web component) can't get its template
(1 answer)
Closed 3 years ago.
I was trying to understand how web components work so I tried to write a small app that I served on a webserver (tested on Chrome which support rel="import"):
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="import" href="my-app.html" />
</head>
<body>
<my-app />
</body>
</html>
my-app.html:
<template id="template">
<div>Welcome to my app!</div>
</template>
<script>
class MyApp extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: "open"});
const template = document.getElementById("template");
const clone = document.importNode(template.content, true);
shadow.appendChild(clone);
}
}
customElements.define("my-app", MyApp);
</script>
But it doesn't seem to work. The <my-app /> tag is not rendered at all in the DOM and I get this error on the console:
Uncaught TypeError: Cannot read property 'content' of null
What cannot I retrieve the template node? What am I doing wrong?
What I would also like to know is if I am allowed to write an HTML document without the boilerplate code (doctype, head, body, ...), because it's meant to describe a component and not an entire document to be used as is. Is it allowed by the HTML5 specs and/or is it correctly interpreted by a majority of browsers?
Thank you for your help.
While inside the template, don't use the document global:
<template id="template">
<div>Welcome to my app!</div>
</template>
<script>
class MyApp extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: "open"});
// while inside the imported HTML, `currentDocument` should be used instead of `document`
const currentDocument = document.currentScript.ownerDocument;
// notice the usage of `currentDocument`
const template = currentDocument.querySelector('#template');
const clone = document.importNode(template.content, true);
shadow.appendChild(clone);
}
}
customElements.define("my-app", MyApp);
</script>
Plunker demo: https://plnkr.co/edit/USvbddEDWCSotYrHic7n?p=preview
PS: Notes com compatibility here, though I assume you know HTML imports are to be deprecated very soon.

Using polymer with external js files

I want to use trumbowyg.js in my polymer element, it includes jquery.js and trumbowyg.js. It works fine in Firefox but not in chrome.
It gives error, may be because shadow dom lookup/separation in chrome. The error happens where ever trumbowyg.js uses "this".
Whats going wrong here? What should I do differently?
I am using Polymer 2.0
error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at trumbowyg.js:1544
my-notes.html
<link rel="import" href="../polymer/polymer-element.html">
<link rel="import" href="../bower_components/trumbowyg/trumbowyg.html">
<dom-module id="my-notes">
<template>
<link rel="stylesheet" href="../bower_components/trumbowyg/dist/ui/trumbowyg.min.css">
<firebase-auth user="{{user}}" signed-in="{{signedIn}}"></firebase-auth>
<div class="card">
<div id="trumbowygd">hello</div>
</div>
</template>
<script>
class MyNotes extends Polymer.Element {
static get is() { return 'my-notes'; }
static get properties() {
return {
user: {
type: Object,
observer: '_shownotearea'
},
};
}
_shownotearea(){
var myFineElement = this.$.trumbowygd;
myFineElement.innerHTML="hello nice meeting you";
$(myFineElement).trumbowyg({});
}
</script>
</dom-module>
trumbowyg.html
<script src="../jquery/dist/jquery.min.js"></script>
<script src="dist/trumbowyg.js"></script>
This doesnt seem to be working
jQuery plugins and Polymer elements
The short answer is this plugin probably won't work with native Shadow DOM.
Likely trumbowyg is trying to query the document to look for some element. Shadow DOM creates markup encapsulation so you can't use $() or document.querySelector to look for things inside of shadow roots. In general I recommend not using jQuery plugins inside of Shadow DOM for this reason.

angularjs directive displays json during page load

I'm building my first AngularJS dynamic form, built based on information received from a JSON file using AngularJS directive.
Everything works, my issue is that the JSON code is getting displayed while the page is loaded - once the page is loaded the JSON code disappears.
Am I doing something wrong?
Check http://plnkr.co/edit/v4jOwuF6jmZfORlNbvIB?p=preview to see the behavior, click on "Stop"/"Start" multiple times to see the behavior.
HTML code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.2" src="https://code.angularjs.org/1.4.0-beta.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="ViewCtrl">
<div ng-repeat="page in form.form_pages">
<div ng-repeat="field in page.page_fields" class="form-group">
<field-directive field="field" ng-form="subForm"></field-directive>
</div>
</div>
</body>
js code:
'use strict';
angular.module('myApp',[])
.controller('ViewCtrl', ['$scope', function($scope) {
var jsonStr='{"form_id":"1","form_name":"My Test Form","form_pages":{"1":{"page_id":1,"page_title":"My First Tab","page_hide":false,"page_fields":{"1":{"field_id":1,"field_title":"First Name","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"2":{"field_id":2,"field_title":"Last Name","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"3":{"field_id":3,"field_title":"Gender","field_type":"textfield","field_value":"0","field_required":true,"field_disabled":false},"4":{"field_id":4,"field_title":"Email Address","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"5":{"field_id":5,"field_title":"Password","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"6":{"field_id":6,"field_title":"Birth Date","field_type":"textfield","field_value":"1981-01-10T06:00:00.000Z","field_required":true,"field_disabled":false},"7":{"field_id":7,"field_title":"Your browser","field_type":"textfield","field_value":"2","field_required":false,"field_disabled":false},"8":{"field_id":8,"field_title":"Additional Comments","field_type":"textarea","field_value":"","field_required":true,"field_disabled":false},"9":{"field_id":9,"field_title":"I accept the terms and conditions.","field_type":"textfield","field_value":"0","field_required":true,"field_disabled":false}}}}}';
$scope.form = JSON.parse(jsonStr);
}])
.directive('fieldDirective',function($http, $compile) {
var linker = function(scope, element) {
// GET template content from path
var templateUrl = "textfield.html";
$http.get(templateUrl).success(function(data) {
element.html(data);
$compile(element.contents())(scope);
});
}
return {
template: '<div>{{field}}</div>',
restrict: 'E',
scope: {
field: '='
},
link: linker
};
})
textfield.html - the html template:
<div class="row" ng-form="subForm" ng-class="{'has-success': subForm[field.field_id].$invalid}">
<div class="col-sm-5">{{field.field_title}}:</div>
<div class="col-sm-7">
<input type="text"
placeholder="{{field.field_title}}"
ng-model="field.field_value"
value="{{field.field_value}}"
ng-required="field.field_required"
ng-disabled="field.field_disabled"
class="form-control"
id = "{{field.field_id}}"
name = "{{field.field_id}}" >
<div ng-show="subForm[field.field_id].$touched && subForm[field.field_id].$error && subForm[field.field_id].$invalid">Field '{{field.field_title}}'
<span ng-show="subForm[field.field_id].$error.required"> is required.</span>
</div>
</div>
</div>
Thank you.
http://plnkr.co/edit/YC9p0UluhHyEgAjA4D8R?p=preview
Basically instead of adding the loaded template into the element then compiling it in place I just compile the string then insert the compiled element directly
element.append($compile(data)(scope));
Seems you can still see a delay but this might be the async loading of the template causing that, would need to debug in the network panel and do some profiling or logging to see exactly what's going on.
Edit
Made a fork of the plnkr to show one with the template inlined so there's no delay fetching it with $http http://plnkr.co/edit/Tnc3VOeI8cELDJDHYPTO?p=preview instead just grabbing it synchronously from the template cache and using ng-template in a script block to have it loaded in advance.

Windows 8 click event hander only works once WinJS

I'm coding a Windows 8 application in JavaScript and HTML5. I wish to show a dialog box when clicking a button.
I have specified the event handler in the default.js file like so:
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll().done(function () {
// Get the login button on the home page
var login_button = document.getElementById("login_submit");
// Set an event handler on the login button
login_button.addEventListener("click", UserActionLogin, false);
}));
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
function UserActionLogin(mouseEvent) {
var message_dialog = new Windows.UI.Popups.MessageDialog("Sorry, we were unable to log you in!" + mouseEvent.y.toString()).showAsync();
}
app.start();
})();
My HTML markup is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HelloWorld</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<!-- HelloWorld references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="wrapper">
<div class="login_box">
<form method="post">
<input type="text" name="login_username" />
<input type="password" name="login_password" />
<input type="submit" id="login_submit" name="login_submit" />
</form>
</div>
</div>
</body>
</html>
When I click the login_submit button when the application loads, it shows the dialog box just fine.
But when I click it for a second time it doesn't work, it's like it's forgotten about the Event Handler.
The problem is having the element in there, which you don't need in an app because you won't want to have the submit button repost/reload the page with the form contents. You're effectively reloading the page but the activated handler isn't called in that case (the page is loaded as a post rather than a request), so you lose the event handler.
If you delete the element, then it works just fine. I'm also told that if you use type="button" instead of type="submit" then it should work. But in an app, you'll typically collect the data from the controls and save that in other variables, navigating to another "page" in the app using the WInJS navigation and page control mechanisms, which keeps you on default.html without changing script context.
Also, I notice that you're still referring to the RC version of WinJS. Since Win8 is officially released now, be sure to develop against the released version of the system and using the most recent tools.
The problem is your use of the form element, which is causing your HTML to be reloaded when you click the button - this replaces the element you set up the event handler for, meaning that subsequent clicks don't invoke your handler function.
Remove the form element and you will get the behavior you expect, as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App7</title>
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<div id="wrapper">
<div class="login_box">
<input type="text" name="login_username" />
<input type="password" name="login_password" />
<input type="submit" id="login_submit" name="login_submit" />
</div>
</div>
</body>
</html>
If you really need the form element for some reason (perhaps because you are using a JS library which expects it), then you can prevent the problem by stopping the form being submitted in your event handler function, as follows:
function UserActionLogin(mouseEvent) {
var message_dialog = new Windows.UI.Popups.MessageDialog("Sorry, we were unable to log you in!" + mouseEvent.y.toString()).showAsync();
mouseEvent.preventDefault();
}
The call to preventDefault stops the form being posted but allows you to keep the form element in the document.

Wicket: DropDown box with checkboxes for multiple selection

I need to compactly present multi-selection inside a drop-down box in Wicket by having a check box next to each value in the drop down box. I'm thinking of using ListView with CheckBox and Label as a component for DropDownChoice but then I am not sure how to proceed further.
You can use some javascript library applied to Wicket's ListMultipleChoice (which generates a [select multiple="multiple"] HTML tag. I've found one (jQuery UI MultiSelect Widget, hosted at GitHub) implemented as a jQuery plugin, which works very well. Thanks to #erichynds!
The Page class is just a plain-old Wicket page, and all you have to do is to import the scripts/stylesheets, and call a single function (highly configurable):
HomePage.java:
public class HomePage extends WebPage {
List<String> selection = new ArrayList<String>();
public HomePage() {
add(CSSPackageResource.getHeaderContribution(HomePage.class, "jquery.multiselect.css"));
add(JavascriptPackageResource.getHeaderContribution(HomePage.class, "jquery.multiselect.min.js"));
add(new FeedbackPanel("feedback"));
Form form = new Form("form") {
#Override
protected void onSubmit() {
info(selection.toString());
}
};
form.add(new ListMultipleChoice("list",
new PropertyModel(this, "selection"),
Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H")));
add(form);
}
}
HomePage.html
<html xmlns:wicket="http://wicket.apache.org">
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/cupertino/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select").multiselect();
});
</script>
</head>
<body>
<div wicket:id="feedback"></div>
<form wicket:id="form">
<select wicket:id="list"></select>
<br/>
<input type="submit">
</form>
</body>
</html>
Alas Wicket is used to generate HTML, and in HTML there is no facility to have a drop-down with checkboxes. (In Swing or another Windowing UI, this would be possible, and your approach would be correct.)
Take a look on the internet for example code for HTML which can cause a similar effect (e.g. a <div> which is shown / not shown when you click on the value you're editing). For example I found this thread here: http://www.webdeveloper.com/forum/showthread.php?t=182976