Search code examples
angularangular-materialangular-formsmat-autocomplete

Angular mat autocomplete not showing if input setValue


When I click the input element, the autocomplete options are shown. But when I dynamically change the value of the input element, the autocomplete options are not shown.

<mat-form-field>
    <input type="text"
        [formControl]="dialTextControl"
        [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
        <mat-optgroup *ngFor="let group of dialerUsersGroup" [label]="group.type">
            <mat-option *ngFor="let user of group.users" [value]="user.number">
              {{user.name}}
            </mat-option>
        </mat-optgroup>
    </mat-autocomplete>
</mat-form-field>


dialTextControl = new FormControl();
ngOnInit() {
    this.dialTextControl.valueChanges
      .subscribe(data => {
        this.filterGroups(data);
      });
}

filterGroups(value: string) {
    // my logic for updating dialerUsersGroup
}

setCustomValue() {
    this.dialTextControl.setValue('something'); // this does not make the autocomplete appear
}

How can the autocomplete be made visible when the input value is changed dynamically?


Solution

  • I assume you want to show the panel as soon as you set the value.for that to happen

    Html: Use template reference for input too

    <mat-form-field>
        <input type="text"
            [formControl]="dialTextControl"
           #autoCompleteInput  [matAutocomplete]="auto" >
        <mat-autocomplete #auto="matAutocomplete">
            <mat-optgroup *ngFor="let group of dialerUsersGroup" [label]="group.type">
                <mat-option *ngFor="let user of group.users" [value]="user.number">
                  {{user.name}}
                </mat-option>
            </mat-optgroup>
        </mat-autocomplete>
    </mat-form-field>
    

    and in ts

    @ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;
    
    setCustomValue() {
        this.dialTextControl.setValue('something'); // this does not make the autocomplete appear
        this.autocomplete.openPanel();
    }
    

    Stackblitz:https://stackblitz.com/edit/angular-o2itzp