【问题标题】:Angular mat autocomplete not showing if input setValue如果输入 setValue,角度垫自动完成不显示
【发布时间】:2020-03-29 20:51:19
【问题描述】:

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

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

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

【问题讨论】:

  • 请也添加filterGroups功能
  • @Supercool。那个 filterGroups 方法的代码太长了。它有效,filterGroups 代码不是问题
  • 我只是想看看你是如何过滤的......如果它太长那很好
  • 你在上面的代码中使用了响应式表单吗?
  • @Supercool。是的

标签: angular angular-material angular-forms mat-autocomplete


【解决方案1】:

我假设您希望在设置值后立即显示面板。为此

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2018-12-24
    • 2016-01-14
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多