gpt4 book ai didi

Angular 7和angular material如何获取mat-select的选定选项文本而不是其值

转载 作者:太空狗 更新时间:2023-10-29 17:31:18 31 4
gpt4 key购买 nike

我需要获取 Material 下拉列表的选定文本<mat-select>而不是它的值:

<ng-container matColumnDef="fr">
<th mat-header-cell *matHeaderCellDef> Family Rel. </th>
<td mat-cell *matCellDef="let element; let i = index;">
<div [formGroupName]="i">
<mat-form-field color="warn" appearance="outline">
<mat-label>Family Relation</mat-label>
<mat-select #familyRelation (selectionChange)="onChange(element, i, 'hh')" id="family_relation"
formControlName="fr" placeholder="Family Relation">
<mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.family_relation_id">
{{familyRelation.family_relation_type}}
</mat-option>
</mat-select>
</mat-form-field>&nbsp;
</div>
</td>
</ng-container>

这是我正在尝试做的事情:

@ViewChild('familyRelation') familyRel: ElementRef;

并且在下拉列表的更改选择上:

onChange(data, i, type) {
let c = this.familyRel.nativeElement.innerText;
console.log(c)
}

我有以下错误:

ERROR TypeError: Cannot read property 'innerText' of undefined at

当我删除 innerText 时,安慰值是:

undefined

如您在 stackblitz 中所见,我需要什么, 如果我选择 Parent , 我想得到 Parent进入一个变量而不是1这是它的 id .

请注意element , ihh(selectionChange)=onChange(element,...)稍后在函数中使用,所以现在忘记它。

最佳答案

很抱歉我迟到了。我真的很害怕阅读上面的所有答案......

该解决方案比任何建议的答案都简单直接得多,因为选择组件只是将所选模型作为 selectionChange 参数的一部分传递。

但首先,对您的示例进行一些更正。你已经声明了一个接口(interface),所以使用它:

export interface FamilyRelation {
id: number;
type: string;
}

因此,在您的构造函数中:

 constructor() {
this.familyRelationArray=[
{
id: 1,
type: 'Parent'
},
{
id: 2,
type: 'Sister'
}
]
}

而不是你在 StackBlitz 中放入的内容......那么你的 View 将变成这样:

<mat-select (selectionChange)="onChange($event)" id="family_relation" placeholder="Family Relation">
<mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.id">
{{familyRelation.type}}
</mat-option>
</mat-select>

不需要每个 mat-option 的 (click) 处理程序,因为这不是必需的,如果您有很多选项,可能会导致性能问题。现在,在 Controller 上:

onChange(ev: any) {
let optionText = ev.source.selected.viewValue;
console.log(optionText);
}

或者,如果您愿意,输入变体:

onChange(ev: MatSelectChange) {
let optionText = (ev.source.selected as MatOption).viewValue; //use .value if you want to get the key of Option
console.log(optionText);
}

但不要忘记导入...

import { MatSelectChange } from '@angular/material/select';
import { MatOption } from '@angular/material/core';

关于Angular 7和angular material如何获取mat-select的选定选项文本而不是其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652924/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com