簡體   English   中英

mat-select(Angular Material):當用戶選擇默認值時,selectionChange 不會觸發

[英]mat-select (Angular Material): selectionChange not firing when user selects the default value

(可能是重復的,但找不到與此特定問題有關的問題)

使用 Angular 13 和 Angular-Material 13.3.9。 我實現了一個簡單的 mat-select 來選擇過濾器(全部、每月、每年和創建者)。 mat-select 提供一個預選值,即每月。 每當用戶更改 mat-selects 值時,selectionChange EventEmitter 就會觸發一個事件,到目前為止它工作正常 - 除了一個問題:

每當用戶選擇不同的值(例如每年),然后再次選擇預選值(每月)時,不會觸發 selectionChange 事件。

為什么? 在這種特定情況下,我怎樣才能讓事件觸發?

已經測試過:

  • 嘗試使用其他預選值,例如每年。 問題與每月相同,但是當用戶再次選擇每年時,當然不會觸發該事件。
  • 硬編碼 mat-options 並沒有改變行為。
  • 刪除翻譯管道只是為了確保它不會干擾並沒有改變行為。

.html:

<mat-form-field appearance="fill">
  <mat-label>{{ 'filterprojects.showas' | translate }}</mat-label>
  <mat-select [(value)]="selectedMainFilter.value" (selectionChange)="onMainFilterChange()">
    <mat-option [value]="option.value" *ngFor="let option of mainFilters">{{ 'filterprojects.' + option.viewValue | translate }}</mat-option>
  </mat-select>
</mat-form-field>

.ts

@Component({
  selector: 'app-filterprojects',
  templateUrl: './filterprojects.component.html',
  styleUrls: ['./filterprojects.component.css']
})
export class FilterprojectsComponent implements OnInit {

  //Filter-Values
  mainFilters: MainFilterElement[] = [
    { value: 'all', viewValue: 'filterall' },
    { value: 'yearly', viewValue: 'filteryearly' },
    { value: 'monthly', viewValue: 'filtermonthly' },
    { value: 'creator', viewValue: 'filtercreator' }
  ];

  selectedMainFilter: MainFilterElement = this.mainFilters[2]; //Select the Monthly-Filter by default
  
  public onMainFilterChange() {
    console.log("Hi! I will not be fired, if the monthly-mainFilter is selected by the user.");
  }
}

在組件而不是模板內分配selectedMainFilter

selectedMainFilter: string = this.mainFilters[2].value;

並在模板中使用

<mat-select [(value)]="selectedMainFilter" ...

現在您可以獲得選定的值

onMainFilterChange() {
 console.log(this.selectedMainFilter)
}

暫無
暫無

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

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