Angular 如果输入 setValue,mat 自动完成不显示

Angular mat autocomplete not showing if input setValue

当我单击输入元素时,会显示自动完成选项。但是当我动态更改输入元素的值时,自动完成选项没有显示。

<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
}

当输入值动态变化时,如何使自动完成可见?

我假设您想在设置 value.for 后立即显示面板

Html: 也使用模板参考输入

<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>

并在 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