Last active
October 20, 2023 11:45
-
-
Save dpedro/21df6fa15f6e63b008d55ad6fdba3219 to your computer and use it in GitHub Desktop.
Single form control (without FormGroup)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
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 | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a typo in [formControl]="seachControl"
<input type="search" [formControl]="searchControl">
Otherwise it will always error out "Cannot find control with unspecified name attribute"