材料自动完成关闭引导下拉列表

时间:2018-04-14 07:47:01

标签: javascript angular bootstrap-4 angular-material

我已经实现了一个非常简单的材料自动完成。

使用Angular 5,使用bootstrap 4下拉列表显示表单

我发现当我将自动填充功能放入下拉列表并选择自动填充内的项目时,它会关闭整个下拉列表。

自动填充本身,按预期工作

HTML:

 <div class="btn-filter">
<button class="btn" id="user-filter" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Filter <span class="ion-levels"></span></button>
  <div class="dropdown-menu" id='dClose' aria-labelledby="user-filter" style="width: 400px; height: 300px">
      <form class="example-form">
          <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">
                <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
                <span>{{ state.name }}</span> |
                <small>Population: {{state.population}}</small>
              </mat-option>
            </mat-autocomplete>
          </mat-form-field>
      </form>
  </div>

打字稿/ Javascript,用于自动完成:

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

      filterStates(name: string) {
        return this.states.filter(state =>
          state.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
      }

这仅用于测试目的,我不知道最佳实践,但我在ngAfterViewInit中设置了一个时间

   ngAfterViewInit() {
        setTimeout(()=>{
                document.getElementById('dClose').addEventListener('click', (e)=>{
                  e.stopImmediatePropagation();
                });//this works, when the actual dropdown itself is clicked it does not close
                document.getElementById('dClose').addEventListener('onblur', (e)=>{
                  e.stopImmediatePropagation();
                });//this does not work, when the autocomplete is selected, the dropdown closes
            }, 3000)
      }

赞赏任何想法

1 个答案:

答案 0 :(得分:0)

我建议访问自动填充MatAutocompleteTrigger。它有openPanel方法。最好使用Angular的@Viewchild而不是document.getElementById ...

组件类:

  import { MatAutocompleteTrigger } from '@angular/material';
  ...    
  @ViewChild(MatAutocompleteTrigger) autoTrigger: MatAutocompleteTrigger;
  ...
  onSelect(): void { setTimeout(() => {this.autoTrigger.openPanel()}, 10)}

组件模板

   <mat-autocomplete " (optionSelected)="onSelect() ...>

<强> DEMO