簡體   English   中英

如何將Angular 5 Material Select下拉菜單(mat-select)更改為打字稿代碼/文件中的選項之一?

[英]How can I change an Angular 5 Material Select dropdown (mat-select) to one of the options in typescript code/file?

所以我有一個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的選定值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM