component
ng2 controls
Component view
- pristine
- dirty
- touched
- untouched
- errors
- valid
import { FORM_DIRECTIVES } from '@angular/common'
@Component({
selector: "my-form",
directives: [FORM_DIRECTIVES],
template: `<input type="text" [(ngModel)]="name">`
})
class MyForm {
name: string
}
@Component({
selector: "my-form",
template: `
<input type="text" [(ngModel)]="name" #field="ngModel">
<pre>
{{ field.valid }}
</pre>
`
})
class MyForm {
name: string
}
<form [ngFormModel]="loginForm" (submit)="doLogin($event)">
<input ngControl="email" type="email" placeholder="Your email">
<input ngControl="password" type="password" placeholder="Your password">
<button type="submit">Log in</button>
</form>
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';
@Component({
selector: 'login-page',
templateUrl: 'login-page.html'
})
export class LoginPage {
constructor(private _formBuilder: FormBuilder) {
this.loginForm = _formBuilder.group({
email: ["", Validators.required],
password: ["", Validators.required]
});
}
doLogin(event) {
console.log(this.loginForm.value);
event.preventDefault();
}
}
this.loginForm = new ControlGroup({
email: new Control("email", Validators.required),
password: new Control("password", Validators.required)
});
function containsTroll(c: Control) {
if(c.value.indexOf('troll') >= 0) {
return {
noTroll: true
}
}
return null
}
this.loginForm = _formBuilder.group({
email: ['', containsTroll]
password: ['', Validators.required],
});
// Component
this.name = new Control('', Validators.minLength(4));
// View
<input required type="text" ngControl="name" />
<div [hidden]="name.dirty && !name.valid">
<p [hidden]="name.errors.minlength">
Your name needs to be at least 4 characters.
</p>
</div>
interface ValidationResult {
[key:string]:boolean;
}
// Component
function containsTroll(c: Control) {
if(c.value.indexOf('troll') >= 0) {
return {
noTroll: true
}
}
return null
}
this.name = new Control('', containsTroll);
// View
<input required type="text" ngControl="name" />
<div [hidden]="name.dirty && !name.valid">
<p [hidden]="name.errors.noTroll">
There is "troll" in your name ...
</p>
</div>
// Component
function exists(c: Control): Promise<ValidationResult> {
let q = new Promise((resolve, reject) => {
setTimeout(() => {
if (c.value === 'George') {
resolve({"usernameExists": true})
} else {
resolve(null)
}
}, 1000)
})
return q
}
this.name = new Control('', Validators.required, exists);
// View
<input required type="text" ngControl="name" />
<p [show]="name.pending">
Fetching data from server!
</p>
<div [hidden]="name.dirty && !name.valid && !name.pending">
<p [hidden]="name.errors.required">
Your name is required!
</p>
<p [hidden]="name.errors.usernameExists">
This username already exists! sad ;-(
</p>
</div>
let validators = Validators.compose(Validators.required, containsTroll)
let asyncValidators = Validators.composeAsync(exists, exists1)
this.name = new Control('', validators, validatorsAsync);