Jeyabalan Thavamani
Jeyabalan Thavamani

Reputation: 3327

Angular material auto complete change event not called when component loading?

I used angular material("@angular/material": "7.1.0") auto-complete component and then i used form control instead of ng model, now the problem is, i can't get the auto-complete change event when the component is loading. I was set the value to the auto-complete component on ngOnInint method that time i want to call one method based on the auto-complete value changes.

I have created a code at stackblitz, here is the link: https://stackblitz.com/edit/angular-xmnmpy

Upvotes: 8

Views: 34395

Answers (2)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

Well, first of all, you're not using ngOnInit at all.

Secondly, ngModelChange doesn't work with reactive forms.

You will have to listen to value changes like so:

this.myGroup
    .get('identifier').valueChanges.subscribe(value => console.log('Value changes'));

This is a standard way of listening to value changes with reactive forms.

Here is your StackBlitz.

Upvotes: 5

Anton Skybun
Anton Skybun

Reputation: 1649

You must use optionSelected event on <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChange($event)" >

Example on StackBlitz

You must use in html :

<form [formGroup]="myGroup">
<mat-form-field>
    <input type="text"
          matInput
          [matAutocomplete]="auto"
          formControlName="identifier">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChange($event)" >
      <mat-option *ngFor="let animal of animals"
            [value]="animal.name">
        {{animal.name}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

And in your ts:

  onSelectionChange(event){
    console.log('onSelectionChange called', event.option.value);
  }

Hope I helped you, also if you need help be free to ask me!

Upvotes: 23

Related Questions