Best way to create a reusable Aurelia widget that encapsulates both the label and the edit field - aurelia

I'm trying to create a simple Aurelia reusable widget that encapsulates both a label and a text input field. The idea is to create a library of these reusable UI widgets to make it easier to compose screens and forms - perhaps taking some learnings from "Angular Formly".
text-field.html template:
<template>
<div class="form-group">
<label for.bind="name">${label}</label>
<input type="text" value.two-way="value" class="form-control" id.one-way="name" placeholder.bind="placeHolder">
</div>
</template>
text-field.js view model:
import {bindable} from 'aurelia-framework';
export class TextField {
#bindable name = '';
#bindable value = '';
#bindable label = '';
#bindable placeHolder = '';
}
client.html template snippet (showing usage of text-field):
<text-field name="firstName" value.two-way="model.firstName" label="First Name" placeHolder="Enter first name"></text-field>
<text-field name="lastName" value.two-way="model.lastName" label="Last Name" placeHolder="Enter last name"></text-field>
client.js view model (showing usage of text-field):
class ClientModel {
firstName = 'Johnny';
lastName = null;
}
export class Client{
heading = 'Edit Client';
model = new ClientModel();
submit(){
alert(`Welcome, ${this.model.firstName}!`);
}
}
QUESTION:
When the final HTML is generated, the attributes are "doubled up" by for example having both the id.one-way="name" AND id="firstName" (see below) - why is this and is there a better way to do this entire reusable text field control?:
<input type="text" value.two-way="value" class="form-control au-target" id.one-way="name" placeholder.bind="placeHolder" id="firstName" placeholder="">

That's normal. Same as if you do style.bind="expression" on a div and expression has display:block. You will end up with <div style.bind="expression" style="display:block"/>. The browser ignores style.bind because it is not a known html attribute. You can just ignore the Aurelia one.

Related

Web Component Input radio not in a group

I have the WC <m-form> witch is the wraper for my form and the input fields.
In the renderHTML() of m-form i do this:
renderHTML() {
this.loadChildComponents().then(children => {
Array.from(this.root.querySelectorAll('input'))
.filter(i => i.getAttribute('type') != "hidden").forEach(input => {
const label = this.root.querySelector(`label[for=${input.getAttribute("name")}]`)
const aInput = new children[0][1](input, label, { namespace: this.getAttribute('namespace') || ''})
aInput.setAttribute('type', input.getAttribute('type'))
input.replaceWith(aInput)
})
})
}
This wraps <input> and <label> in an <a-input> WC.
But when I want to do the same with
<input type="radio" id="gender1" name="gender" value="herr">
<label for="gender1">Herr</label>
<input type="radio" id="gender2" name="gender" value="frau">
<label for="gender2">Frau</label>
they are not in a group.
What can i do to get them grouped together but also in the <a-input>?
Here is the Code on the site and what got rendered out.
shadowDOM encapsulates CSS, HTML and behavior
Both you inputs are in shadowDOM. That is like putting them into 2 different IFRAMEs.
They have no clue another input exists
Remove shadowDOM
or, loads more work, add Events to make the inputs communicate with each other

Validate input that derives from custom element in to DynamicForm

I am trying to add validation to custom element that gets generated in dynamic form component to support page for view. I injected Aurelia-Validation in main.ts, and DynamicForm.ts and instantiated. Below is my code.
CUSTOM ELEMENT:
TS File
import { customElement, useView, bindable, bindingMode, inject } from 'aurelia-framework';
#customElement('custom-input')
#useView('./custominput.html')
export class CustomInput {
#bindable({ defaultBindingMode: bindingMode.twoWay }) fieldValue: string;
#bindable public customClass: string;
#bindable public placeHolder: string;
#bindable public fieldName: string;
#bindable public formItem: any;
}
HTML View:
<template>
<input class="${customClass}" custom-class.bind="customClass" type="text" field-value.bind="fieldValue"
value.two-way="fieldValue & validateOnChange" placeholder="${placeHolder}" place-holder.bind="placeHolder"
id="${fieldName}" field-name.bind="fieldName" form-item.bind="formItem" />
</template>
DynamicForm
TS File:
import { bindable, bindingMode, inject } from 'aurelia-framework';
import { ValidationRules, ValidationControllerFactory } from 'aurelia-validation';
#inject(ValidationControllerFactory)
export class DynamicForm {
#bindable public formName: string;
#bindable public formTemplate: Object;
#bindable public callback;
inputItem: HTMLInputElement;
controller = null;
constructor(ValidationControllerFactory) {
this.controller = ValidationControllerFactory.createForCurrentScope();
}
public formValidator(element, field) {
//console.log(element);
}
public bind() {
if (this.formTemplate) {
this.formTemplate[this.formName].fields.forEach((item, i) => {
if (item.validation.isValidate === true) {
ValidationRules.ensure(item.name)
.displayName(item.name)
.required()
.on(this.formTemplate);
}
});
this.controller.validate();
}
console.log(this.controller);
}
}
HTML View:
<template>
<require from="../../elements/custominput/custominput"></require>
<form class="form-horizontal">
<div form-name.bind="formName" class="form-group" repeat.for="item of formTemplate[formName].fields">
<label for="${item.name}" class="col-sm-2 control-label">${item.label}</label>
<div class="col-sm-10" if.bind="item.type === 'text' && item.element === 'input'">
<custom-input router.bind="router" custom-class="${item.classes}" field-value.two-way="item.value"
place-holder="${item.placeHolder}" ref="inputItem" item.bind="formValidator(inputItem, item)"
field-name.bind="item.name" form-item.bind="item">
</custom-input>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-default pull-right" click.delegate="callback()">Submit</button>
</div>
</div>
</form>
<ul if.bind="controller.errors.length > 0">
<li repeat.for="error of controller.errors">${error}</li>
</ul>
</template>
Support page:
This page will load DynamicForm
<template>
<require from="./support.scss"></require>
<require from="../DynamicForm/dynamicform"></require>
<div class="panel panel-primary">
<div class="panel-heading">${pageTitle}</div>
<div class="panel-body">
<dynamic-form form-template.two-way="formTemplate" form-name.two-way="formName" callback.call="processForm()"></dynamic-form>
</div>
</div>
</template>
When I view the support page in browser, I do not get validation in UI. Not sure if validation is position in in nested components/elements. The view is generated like this custominput element -> DynamicForm -> support page
Plunker link for more information:
Any help is really appreciated. :)
Two major issues:
1. Rules shouldn't be stored on fields
Rules are stored on the prototype of an object and pertain to the properties of that object.
You are defining the rules on each individual property, so ultimately it's trying to validate property.property rather than object.property, which doesn't do much as you can see.
You're also declaring the rules every time the form template changes. I basically wouldn't put that logic there; put it closer to where those object come from.
If the objects are declared somewhere in your client code, declare the rules in the same module files
If the objects come from the server, declare the rules on those objects on the same place where you fetch them, right after you fetched them
Either way, those rule declarations don't belong in a change handler.
2. Bindings are missing
The ValidationController needs to know which object or properties you want to validate. It only knows in either of these cases:
Your rules are declared via controller.addObject(obj, rules).
Your rules are declared via ValidationRules.[...].on(obj) and the fields in your html template have & validate following them.
There's several pros and cons with either approach, ultimately you should go with one that gives you least resistance. I would probably go for the second approach because things get more entangled if you declare all rules on your controllers directly.

Aurelia repeater: model.bind is not working for radio buttons

I am creating a set of radio buttons in Aurelia with the code like this:
<div repeat.for="option of options">
<input type="radio" id="${option}_id" name="radio_options" model.bind="option" checked.bind="optionValue"/>
<label for="${option}_id" id="${option}_label">${option}</label>
</div>
However, doing it this way I discovered that model.bind is not working - the optionValue in corresponding class is not populated when radio button is checked. Similarly when some value is assigned to optionValue in the class, the appropriate radio button is not checked. I found this happening only with repeater. Options are numbers in my case. Could you please help me to find out what may be wrong here?
The first problem is that model.bind should be used when working with objects. Since you're working with a primitive type, you should use value.bind instead.
The second problem is that input values are always strings, so when setting an initial value, it must be a string. For example:
Html:
<template>
<div repeat.for="option of options">
<input type="radio" id="${option}_id" name="radio_options" value.bind="option" checked.bind="optionValue"/>
<label for="${option}_id" id="${option}_label">${option}</label>
</div>
<p>Selected Option: ${optionValue} </p>
</template>
JS:
export class App {
options = [ 1, 2, 3, 4 ]
optionValue = '3';
}
If you really want to use int in your view-model, you can create a ValueConverter to convert the value to int when passing it to/from the view. For instance:
export class AsIntValueConverter {
fromView(value) {
return Number.parseInt(value);
}
toView(value) {
return value.toString();
}
}
Usage:
<input type="radio" id="${option}_id" name="radio_options" value.bind="option" checked.bind="optionValue | asInt"/>
Running Example https://gist.run/?id=1465151dd5d1afdb7fc7556e17baec35

How can I compose a VM into a view within an Aurelia validation renderer

I'm trying to use the aurelia-validation plugin to perform validation on a form. I'm creating a custom validation renderer that will change the color of the input box as well as place an icon next to the box. When the icon is clicked or hovered, a popup message appears that will display the actual error message.
Currently, I'm rendering all of this in code manually in the renderer, but it seems like it would be nice to have the html for all of this defined in an html file along with the associated js file to handle the click and hover on the icon. IOW, encapsulate all the error stuff (icon with popup) in a View/ViewModel and then in the render() of my validation renderer, somehow just compose a new instance of this just after the element in question.
Is this possible to do? I've seen how to use <compose></compose> element but I really am trying to avoid having to add that to all of my forms' input boxes.
This is what I currently have in my renderer:
import {ValidationError, RenderInstruction} from 'aurelia-validation'
export class IconValidationRenderer {
render(instruction){
//Unrender old errors
for(let {result, elements} of instruction.unrender){
for(let element of elements){
this.remove(element, result);
}
}
//Render new errors
for(let {result, elements} of instruction.render){
for(let element of elements){
this.add(element, result)
}
}
}
add(element, result){
if(result.valid)
return
//See if error element already exists
if(element.className.indexOf("has-error") < 0){
let errorIcon = document.createElement("i")
errorIcon.className = "fa fa-exclamation-circle"
errorIcon.style.color = "darkred"
errorIcon.style.paddingLeft = "5px"
errorIcon.id = `error-icon-${result.id}`
errorIcon.click = ""
element.parentNode.appendChild(errorIcon)
element.classList.add("has-error")
element.parentNode.style.alignItems = "center"
let errorpop = document.createElement("div")
let errorarrow = document.createElement("div")
let errorbody = document.createElement("div")
errorpop.id = `error-pop-${result.id}`
errorpop.className = "flex-row errorpop"
errorarrow.className = "poparrow"
errorbody.className = "flex-col popmessages"
errorbody.innerText = result.message
console.log("Computing position")
let elemRec = errorIcon.getBoundingClientRect()
let elemH = errorIcon.clientHeight
errorpop.style.top = elemRec.top - 10 + "px"
errorpop.style.left = elemRec.right + "px"
errorpop.appendChild(errorarrow)
errorpop.appendChild(errorbody)
element.parentNode.appendChild(errorpop)
}
}
remove(element, result){
if(result.valid)
return
element.classList.remove("has-error")
let errorIcon = element.parentNode
.querySelector(`#error-icon-${result.id}`)
if(errorIcon)
element.parentNode.removeChild(errorIcon)
//Need to remove validation popup element
}
}
Thanks for any help you can offer.
P.S. At this point, I am not implementing a click or hover like I mentioned -- that is something that I would like to do but I'm not even sure how at this point. Would be more straight forward if I can compose a VM.
EDIT
I was pointed to this article by someone on the Aurelia Gitter channel. I've tried implementing the TemplatingEngine but clearly I'm not going about it the right way. Here's what I have.
add-person-dialog.js //VM that has form with validation
import {TemplatingEngine,NewInstance} from 'aurelia-framework'
import {ValidationController} from 'aurelia-validation'
import {IconValidationRenderer} from './resources/validation/icon-validation-renderer'
export class AddPersonDialog {
static inject = [NewInstance.of(ValidationController),TemplatingEngine]
constructor(vc, te){
this.vc = vc
this.vc.addRenderer(new IconValidationRenderer(te))
}
icon-validation-renderer.js
//Plus all the other bits that I posted in the code above
constructor(te){
this.te = te
}
add(element, result){
if(result.valid) return
if(element.className.indexOf("has-error") < 0 {
//replaced there error icon code above with this (as well as a few different variations
let test = document.createElement("field-error-info")
element.parentNode.appendChild(test)
this.te.enhance({element: test})
}
}
field-error-info.html
<template>
<require from="./field-error-info.css" ></require>
<i class="fa fa-exclamation-circle" click.delegate="displayMessage = !displayMessage" mouseenter.delegate="displayMessage = true" mouseleave.delegate="displayMessage = false"></i>
<div show.bind="displayMessage" class="flex-row errorpop" style="left:300px">
<div class="poparrow"></div>
<div class="flexcol popmessages">Message 1</div>
</div>
</template>
Ultimately, <field-error-info></field-error-info> gets added to the DOM but doesn't actually get rendered. (Incidentally, I also tried adding <require from='./elements/field-error-info'></require> in the add-person-dialog.html.
You could create a form control custom element that encapsulates the error icon and tooltip logic. The element could expose two content projection slots to enable passing in a label and input/select/etc:
<template>
<div validation-errors.bind="errors"
class="form-group ${errors.length ? 'has-error' : ''}">
<!-- label slot -->
<slot name="label"></slot>
<!-- input slot -->
<slot name="input"></slot>
<!-- icon/tooltip stuff -->
<span class="control-label glyphicon glyphicon-exclamation-sign tooltips"
show.bind="errors.length">
<span>
<span repeat.for="errorInfo of errors">${errorInfo.error.message}</span>
</span>
</span>
</div>
</template>
Here's how it would be used:
<template>
<require from="./form-control.html"></require>
<form novalidate autofill="off">
<form-control>
<label slot="label" for="firstName" class="control-label">First Name:</label>
<input slot="input" type="text" class="form-control"
value.bind="firstName & validateOnChange">
</form-control>
<form-control>
<label slot="label" for="lastName" class="control-label">Last Name:</label>
<input slot="input" type="text" class="form-control"
value.bind="lastName & validateOnChange">
</form-control>
</form>
</template>
Live example: https://gist.run/?id=874b100da054559929d5761bdeeb651c
please excuse the crappy tooltip css

Aurelia Two Way Binding Text Field Not Working

Two way binding seems to not update the view unless you type in a text field. So I am using a vanilla date picker (rome). Like most date pickers it pops up a calendar to select your date.
Problem:
Once you click a date from the date picker it will properly place the
date in the text box. It does not however update the two-way binding.
But if I manually type a date in the text box the two binding works
properly and is reflected up to schedule.html
schedule.html
<template>
<require from="../../shared/components/date-range-picker"></require>
<require from="../../shared/components/time-range-picker"></require>
<div>${data.dateTime.openDate}</div> <!-- This doesn't update -->
<date-range-picker containerless date-range.two-way="data.dateTime"></date-range-picker>
<time-range-picker containerless time-range.two-way="data.dateTime"></time-range-picker>
</template>
date-range-picker.html
<template>
<div class="form-group input-button-group input-group date">
<input type="text" class="form-control" id="open" value.bind="dateRange.openDate" class="form-control"
placeholder="Select a Start Date" />
<span class="input-group-addon"><i class="icon-ion-calendar"></i></span>
</div>
<div class="form-group input-button-group input-group date">
<input type="text" class="form-control" id="close" value.bind="dateRange.closeDate" class="form-control"
placeholder="Select a Close Date" />
<span class="input-group-addon"><i class="icon-ion-calendar"></i></span>
</div>
</template>
date-range-picker.js
import { bindable, bindingMode } from 'aurelia-framework';
import rome from 'rome';
import 'rome/dist/rome.css';
export class DateRangePicker {
#bindable({ defaultBindingMode: bindingMode.twoWay }) dateRange;
attached() {
const open = document.getElementById('open');
const close = document.getElementById('close');
rome(open, {
time: false,
dateValidator: rome.val.beforeEq(close),
});
rome(close, {
time: false,
dateValidator: rome.val.afterEq(open),
});
}
}
You could dispatch the change event of the input element. I've done this using a customAttribute, but you can still use customElements. Like this:
rome.js
import {inject} from 'aurelia-dependency-injection';
import {customAttribute} from 'aurelia-templating';
#inject(Element)
#customAttribute('rome')
export class Rome {
constructor(element) {
this.element = element;
}
attached() {
let picker = rome(this.element);
picker.on('data', () => {
this.element.dispatchEvent(new Event('change'));
});
}
}
Usage
<require from='./rome'></require>
<input type="text" rome value.bind="selectedDate">
${selectedDate}