To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.
Observables allow not only to use the subscribe
method (something similar to the then
method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.
I mean you can specify at this level the debounce time with the debounceTime
method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:
this.form.valueChanges
.debounceTime(500)
.subscribe(data => console.log('form changes', data));
You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap
method:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
You even go further by linking the returned observable directly to a property of your component:
this.list = this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
and display it using the async
pipe:
<ul>
<li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>
Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).
Hope it helps you, Thierry