避免 Angular Material Autocomplete 显示 mat-options 当它为空时

Rea*_*eik 5 typescript angular-material angular

我开始在我的一个项目中使用 Material。查看<mat-autocomplete>文档网站的示例...

<mat-form-field class="example-full-width">
  <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
    <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
    <span>{{state.name}}</span> |
  </mat-option>
</mat-autocomplete>
Run Code Online (Sandbox Code Playgroud)

ts:

    export class AutocompleteOverviewExample {        
      stateCtrl = new FormControl();
      filteredStates: Observable<State[]>; 
      states: State[] = [
            { name: 'Arkansas'  },
            ...
            { name: 'Texas' }
          ];

          constructor() {
            this.filteredStates = this.stateCtrl.valueChanges
              .pipe(
                startWith(''),
                map(state => state ? this._filterStates(state) : this.states.slice())
              );
          }

          private _filterStates(value: string): State[] {
            const filterValue = value.toLowerCase();
            return this.states.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);

            // Material example, its basically a ._http.get(value).map
          }
        }
Run Code Online (Sandbox Code Playgroud)

<mat-option>单击输入字段时将部署该列表。我想避免这种情况,只在 X 时显示选项(他们写了 3 个或更多字符,它是一个包含 5 或 10 个元素的“小”列表等)。

如何修改此行为并动态执行?

Sha*_*anu 8

这是库中的默认行为。要自定义它,您可以在更改自动完成的模型值时使用 CSS 隐藏自动完成选项,然后设置您希望在输入文本上具有的最小长度,然后相应地显示自动完成选项。将视图代码更新为:

<mat-form-field class="example-full-width">
  <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl" 
  (ngModelChange)="updatedVal($event)">
  <mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let state of filteredStates | async" [value]="state.name" 
    [ngClass]="{'hide-autocomplete': !showAutocomplete}">
   <span>{{state.name}}</span> |
   </mat-option>
  </mat-autocomplete>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

在这里,我在输入字段上添加了 ngModelChange 以检查模型更改。在 mat-option 上,我添加了 ngClass。在哪里

.hide-autocomplete { display: none; }
Run Code Online (Sandbox Code Playgroud)

在课堂上,updatedVal 方法是:

updatedVal(e) {
  if(e && e.length >= 3) {
     this.showAutocomplete = true;
  } else {
     this.showAutocomplete = false;
  }
}
Run Code Online (Sandbox Code Playgroud)

所以只有当输入长度小于 3 时,隐藏类才会被添加到 mat-option。

演示示例