Angular Js 2 - Forms - EventEmitter, Observable -
Observing changes in a control or changes in the form.

import { Component } from 'angular2/core';
import {
ControlGroup,
AbstractControl,
FormBuilder,
Validators,
CORE_DIRECTIVES,
FORM_DIRECTIVES
} from 'angular2/common';
@Component({
selector: 'demo-form-with-events',
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
template: `
<div class="ui raised segement">
<h2 class="ui header"></h2>
<form [ngFormModel]="myForm"
(ngSubmit)="onSubmit(myForm.value)"
class="ui form">
<div class="field"
[class.error]="sku.touched && !sku.valid">
<label for="skuInput">SKU</label>
<input type="text"
class="form-control"
id="skuInput"
placeholder="SKU"
[ngFormControl]="sku">
<div *ngIf="!sku.valid" class="ui error message">SKU is invalid.</div>
<div *ngIf="sku.hasError('required')" class="ui error message">SKU is required.</div>
</div>
<div *ngIf="!myForm.valid" class="ui error message">Form is invalid.</div>
<button type="submit" class="ui button">Submit</div>
</form>
</div>
`
})
export class DemoFormWithEvents{
myForm: ControlGroup;
sku: AbstractControl;
constructor(fb: FormBuilder){
this.myForm = fb.group({
'sku': ['', Validators.required]
});
this.sku = this.myForm.controls['sku'];
/* Both Control and ControlGroup have an EventEmitter that we can use to observe changes.
EventEmitter is an observable which means that it conforms to a defined specification for
watching for changes. An Observable is an object that can send multiple values to a
consumer. An Observable has (must have) a subscribe method which accepts a generator and can send it
any number of values.
let subscription = observable.subscribe(generator);
generator is a required argument and it must be an object. Subscribe must return a subscription
object and this object must have an unsubscribe method. A call to the unsubscribe method
should free all references to the generator held by the Observable.
*/
/* We get access to the EventEmitter for the control sku by calling this.sku.valueChanges */
/* Observing the change event for the control sku */
this.sku.valueChanges.subscribe(
(value: string) => {
console.log('sku value changed to: ', value);
}
);
/* Observing the change event for the changes on the form. */
this.myForm.valueChanges.subscribe(
(form: any) => {
console.log('form changed to: ', form);
}
);
}//constructor ends here.
onSubmit(form: any): void {
console.log('You submitted value:', form.sku);
}
}//class DemoFormWithEvents ends here.
No comments:
Post a Comment