所以我有一个Angular 5 Material Data Table,上面有2个过滤器选项,一个通过文本输入,一个通过下拉菜单来过滤特定的字段值。对于下拉菜单,我使用“ mat-select” Angular Material项,其中有2个mat-options,一个为空,另一个基于我拥有的数组,如下所示:

<div class="filterContainer" *ngIf="showDataForm">
  <mat-form-field>
    <input #matInputSearch matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
  </mat-form-field>
</div>
<div class="filterSelectContainer" *ngIf="showDataForm">
  <mat-select placeholder="Search EADDPStage" (selectionChange)="applySelectFilter($event)">
    <mat-option></mat-option>
    <mat-option *ngFor="let stage of EADDPStages[0]" [value]="stage">
      {{stage}}
    </mat-option>
  </mat-select>
</div>


在这里,您可以看到我的.ts代码文件:

  @ViewChild(MatSelect) set contentSelect(contentSelect: ElementRef) {
    this.select = contentSelect;
  }

  @ViewChild('matInputSearch') set matInputSearch(matInputSearch: ElementRef) {
    this.matInputSearchField = matInputSearch;
  }

  public applyFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filter = filterValue;
  }

  public applySelectFilter(event) {
    // This is to reset dropdown filter to empty/no filter
    if (event.value == null) {
      event.value = '';
    }
    this.applyFilter(event.value);
    // set the "Search" field filter to empty string
    this.matInputSearchField.nativeElement.value = '';
  }


现在,我的UI中发生的事情是两个过滤器都可以正常工作,但是我也想(在视觉上)“重置”过滤器。现在,当我在文本框过滤器中键入内容,然后从下拉列表中选择内容时,文本框过滤器的值将设置为空,表明您现在是在下拉列表中进行过滤,而不再在文本输入过滤器字段中进行过滤,以下行将执行此操作:

this.matInputSearchField.nativeElement.value = '';


但是现在我也希望采用其他方法。如果我选择一个下拉过滤器,它会过滤,但是当我想在文本输入过滤器字段中键入内容时,该过滤器也可以正常工作,但是下拉列表中的所选选项仍将是先前选择的值(即使不再使用该过滤器) )。我想要的是在这种情况下,当我在文本输入过滤器字段中键入内容时,我的选择下拉列表将返回到我在HTML中添加的空选项,以指示您不再对下拉列表进行过滤选择,但取决于用户在输入过滤器字段中输入的内容。

我基本上需要的是一种做这样的事情的方法(这是错误的代码,但只是一个指示):

this.select.selectedOption('mat-option-0');


在我的HTML上选择“ mat-select”项的地方,然后给它一个我想要的选择选项或默认选项,在这种情况下,如果您在HTML中看到的为空,则“ mat-option-0”是ID 。

有一个简单的方法吗?

最佳答案

我还没有测试过,但是尝试一下,应该可以工作:
在以下进行更改

HTML:

<mat-select placeholder="Search EADDPStage" (selectionChange)="applySelectFilter($event)" [(ngmodel)]="stageValue">
<mat-option></mat-option>
<mat-option *ngFor="let stage of EADDPStages[0]" [value]="stage">
  {{stage}}
</mat-option>




和组件:

stageValue = '';
public applyFilter(filterValue: string) {
  filterValue = filterValue.trim();
  filterValue = filterValue.toLowerCase();
  this.dataSource.filter = filterValue;
  this.stageValue = '';
}


[(ngmodel)]="stageValue"设置mat-select的选定值。

07-24 09:39
查看更多