我目前有一个角度材料表,它从我拥有的 api 端点返回值。目前,它返回正确的值,但我有选择下拉列表的单元格除外。
这是我的材料表选择下拉列表的片段:
<div class="matTable-container">
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="Active">
<mat-header-cell *matHeaderCellDef > {{ 'Active' | translate}}? </mat-header-cell>
<mat-cell class="is-active" *matCellDef="let product">
<mat-form-field>
<mat-select>
<mat-option *ngFor="let active of activeTypes" [value]="product._isActive">{{product._isActive}}</mat-option>
</mat-select>
</mat-form-field>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns; let even = even; let odd = odd" [ngClass]="{'table-even': even, 'table-odd': odd}"></mat-row>
</mat-table>
</div>
在上面的示例中,尽管我指定了,但目前它是绑定值 ['Yes', 'Yes'] 而不是 ['Yes','No']activeTypes = ['Yes', 'No'];
。它似乎显示了从 api 返回的值和现有值,其中“是”正在替换“否”。
在这种情况下,如何确保绑定正确显示并且下拉列表中的值正确,其中下拉列表中的值应为 ['Yes','No'] 并且绑定/选定的默认值应为 'Yes '对于这个特定的项目?
我上面做错了什么?
你应该绑定到mat-option
数据来自active
这是由创建的*ngFor="let active of activeTypes"
.
<mat-option *ngFor="let active of activeTypes" [value]="active">{{active}}</mat-option>
并将真实数据绑定到mat-select
via [(ngModel)]
<mat-select [(ngModel)]="product._isActive">
...
</mat-select>
对于反应式表单,您应该在创建表单控件时为其分配实际值,并将此表单控件分配给mat-select
通过绑定名称formControlName
.
下面是我创建的一个示例formArray
基于数据源和表单数组的绑定索引(与行索引相同)mat-select
via formControlName
.
<form [formGroup]="form">
<mat-table #table [dataSource]="dataSource" formArrayName="test">
...
<ng-container matColumnDef="active">
<mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
<mat-cell *matCellDef="let element; let i = index;">
<mat-select [formControlName]="i">
<mat-option [value]="active" *ngFor="let active of activeList">
{{ active }}
</mat-option>
</mat-select>
</mat-cell>
</ng-container>
...
</mat-table>
</form>
this.form = this.fb.group({
test: new FormArray(this.dataSource.map(item => new FormControl(item.active)))
});
参考工作demo https://stackblitz.com/edit/angular-riepzk?file=app/table-basic-example.html and 反应式演示 https://stackblitz.com/edit/angular-riepzk-rp5jbf?file=app/table-basic-example.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)