Skip to content

Instantly share code, notes, and snippets.

@dpedro
Last active October 20, 2023 11:45
Show Gist options
  • Save dpedro/21df6fa15f6e63b008d55ad6fdba3219 to your computer and use it in GitHub Desktop.
Save dpedro/21df6fa15f6e63b008d55ad6fdba3219 to your computer and use it in GitHub Desktop.
Single form control (without FormGroup)
<!--
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
});
}
}
@ankitLu
Copy link

ankitLu commented Jun 26, 2020

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment