【发布时间】:2018-12-11 12:13:12
【问题描述】:
我正在尝试使用最新的材料+cdk 为角度构建一个内联可编辑表。
问题
如何使 mat-table 使用
[formGroupName]以便表单字段可以通过其正确的表单路径引用?
这是我目前得到的:Complete StackBlitz example
模板
<form [formGroup]="form">
<h1>Works</h1>
<div formArrayName="dates" *ngFor="let date of rows.controls; let i = index;">
<div [formGroupName]="i">
<input type="date" formControlName="from" placeholder="From date">
<input type="date" formControlName="to" placeholder="To date">
</div>
</div>
<h1>Wont work</h1>
<table mat-table [dataSource]="dataSource" formArrayName="dates">
<!-- Row definitions -->
<tr mat-header-row *matHeaderRowDef="displayColumns"></tr>
<tr mat-row *matRowDef="let row; let i = index; columns: displayColumns;" [formGroupName]="i"></tr>
<!-- Column definitions -->
<ng-container matColumnDef="from">
<th mat-header-cell *matHeaderCellDef> From </th>
<td mat-cell *matCellDef="let row">
<input type="date" formControlName="from" placeholder="From date">
</td>
</ng-container>
<ng-container matColumnDef="to">
<th mat-header-cell *matHeaderCellDef> To </th>
<td mat-cell *matCellDef="let row">
<input type="date" formControlName="to" placeholder="To date">
</td>
</ng-container>
</table>
<button type="button" (click)="addRow()">Add row</button>
</form>
组件
export class AppComponent implements OnInit {
data: TableData[] = [ { from: new Date(), to: new Date() } ];
dataSource = new BehaviorSubject<AbstractControl[]>([]);
displayColumns = ['from', 'to'];
rows: FormArray = this.fb.array([]);
form: FormGroup = this.fb.group({ 'dates': this.rows });
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.data.forEach((d: TableData) => this.addRow(d, false));
this.updateView();
}
emptyTable() {
while (this.rows.length !== 0) {
this.rows.removeAt(0);
}
}
addRow(d?: TableData, noUpdate?: boolean) {
const row = this.fb.group({
'from' : [d && d.from ? d.from : null, []],
'to' : [d && d.to ? d.to : null, []]
});
this.rows.push(row);
if (!noUpdate) { this.updateView(); }
}
updateView() {
this.dataSource.next(this.rows.controls);
}
}
问题
这行不通。控制台产生
错误错误:找不到带有路径的控件:'dates -> from'
似乎[formGroupName]="i" 没有效果,因为使用formArray 时路径应该是dates -> 0 -> from。
我目前的解决方法:对于这个问题,我已经绕过内部路径查找(formControlName="from")并直接使用表单控件:[formControl]="row.get('from')",但是我想知道我如何(或者至少为什么我不能)使用响应式表单的首选方式。
欢迎任何提示。谢谢。
因为我认为这是一个错误,所以我在 angular/material2 github 存储库中注册了 an issue。
【问题讨论】: