我有办法获得下拉列表中所选值的文本,而不是以反应形式获取值吗?
我的脚本如下:
<form [formGroup]="formGroup" formArrayName="test">
<ng-container matColumnDef="fr" formArrayName="test">
<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" >
<mat-label>Family Relation</mat-label>
<mat-select (selectionChange)="onChange(element, i)" 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>
</div>
</td>
</ng-container>
</form>
在更改选择 (selectionChange="onChange(element, i)")
上,我需要同时获取选定的值和文本 .
onChange(data, i)
{
let group = (<FormArray>this.formGroup.get('test')).at(i).value;
let newFr = group['fr'];
console.log('Value: '+newFr);
}
数据是选定行的位置, i
是所选表单数组的索引 .
我尝试使用旧的JavaScript方法:
<HTMLSelectElement>document.getElementById().text
但它给了我一个错误:
[ts]'HTMLElement'类型中不存在属性'text' . [2339]
EDIT
我试过了:
@ViewChild('familyRelation') familyRelation;
和:
<mat-select #familyRelation (selectionChange)="onChange(element, i)" 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>
安慰后:
2 回答
首先,从表单控件中获取值 . 然后通过循环遍历数组获取与value相关的项 . 最后从项目中获取文本
根据您的评论,您需要一种通用的方式来访问您的html元素 . Angular提供easy way to do so
在您的组件内:
创建一个类属性:
@ViewChild('selectFamilyRelation') familyRelation;
然后获取所选选项的文本: