<!-- | |
Sometimes, we don’t need a FormGroup, as our form might only consist of a single form control. Think of a search field that let’s you search for products in an e-commerce application. Technically, we don’t even need a <form> element for that. | |
Angular comes with a directive formControl which doesn’t have to be inside a formGroup. We can simply add it to a single form control and are ready to go: | |
--> | |
<!-- no surrounding form --> | |
<input type="search" [formControl]="seachControl"> | |
<!-- | |
The cool thing about form controls in Angular is, | |
that we can listen reactively for changes that are happening to that control. | |
Every form controls exposes an Observable propery valuesChanges() that we can subscribe to. | |
So in order to get notified about changes in the example above, all we have to do is: | |
--> | |
@Component() | |
export class SearchComponent implements OnInit { | |
searchControl = new FormControl(); | |
ngOnInit() { | |
this.searchControl.valueChanges.subscribe(value => { | |
// do something with value here | |
}); | |
} |
No comments:
Post a Comment