Autocomplete with template based forms

748 views
Skip to first unread message

Johan van den Berg

unread,
Mar 8, 2017, 3:56:24 AM3/8/17
to angular-material2
Hi

The example on the documentation site (https://material.angular.io/components/component/autocomplete) makes use of a FormControl reference to observe a change in the autocomplete's input. I am very much new to angular2 and while I understand the principles behind Observables, I have not been able to figure out how to code the same demo using template-based forms (where I presumably have no access to the FormControl in the Component).

I am trying to create a simple city lookup field that uses rest to retrieve the data. I am able to do this in ngOnInit at the moment, but would love to implement server side filtering when the user types into the text field. Can someone assist with a small example please?

I realise the autocomplete is still in "flux" but hopefully the response here will serve to assist others as well who plan to make use of the component for the future.

Kind regards
Johan

Jeferson Estevo

unread,
Mar 22, 2017, 4:42:48 PM3/22/17
to angular-material2
On template based form, you can name a variable for that input model:

<input type="text" mdInput placeholder="My Placeholder" [(ngModel)]="myField" name="myFieldName" #myFieldModel="ngModel" [mdAutocomplete]="myAutoComplete"/>

Check the #myFieldModel="ngModel". With that, you can inject it on your component, like:

@ViewChild('myFieldModel') myControl: NgModel;

After that, use the "ngAfterViewInit()" method to set your listener (Don't forget to implement the AfterViewInit interface)

ngAfterViewInit(): void {
   
this.filteredOptions = this.myControl.valueChanges
       
.startWith(null)
       
.map(val => val ? this.filter(val) : this.options.slice());
}

On template forms, the component model is created automatically, so you'll need to ask angular to inject it on your component and then, after the component has been injected, you can wrap up a listener for the valueChanges event.
Reply all
Reply to author
Forward
0 new messages