繁体   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