簡體   English   中英

Angular:如何將 mat-option 和所選選項的可見文本放在一起?

[英]Angular: How can I get the mat-option and the visible text of the selected option together?

我還想用選項值獲取我選擇的選項的選項文本。 我需要在下面的代碼中進行哪些必要的更改?

HTML

<mat-select (selectionChange)="changeQuestionValue($event.value)">
  <ng-container *ngFor="let q of QuestionCategory">
    <mat-option *ngIf="q.isActive" [value]="q.id">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>

TS

changeQuestionValue(val) {
    return this.questionValue = val;
}

在 TS 中,我只收到q.id但我也想要q.questionCategoryName

您只需要將 value 屬性更新為[value]="q" 但是,如果您想將整個值存儲在表單控件中,您可以使用compareWith function 返回由選項選擇的 object。 只需定義一個 function 來比較對象並將整個 object 作為值傳遞給mat-option

例如

  public compareWith(obj1: Question, obj2: Question) {
    return obj1 && obj2 && obj1.id === obj2.id;
  }
<mat-select [compareWith]="compareWith" (selectionChange)="onChangeSelect($event.value)">
  <ng-container *ngFor="let q of questionCategories">
    <mat-option *ngIf="q.isActive" [value]="q">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>

這是一個實時示例https://stackblitz.com/edit/en-stackoverflow-62688705

我認為你應該替換[value]="q"

<mat-select (selectionChange)="changeQuestionValue($event.value)">
  <ng-container *ngFor="let q of QuestionCategory">
    <mat-option *ngIf="q.isActive" [value]="q">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>

你需要更換

[值]="q"

價值=“{{q}}”

暫無
暫無

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

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