我刚刚开始使用 Angular 4,我需要开发一个 CRUD 网格,用户可以在其中添加、编辑或删除行。
在我的研究过程中,我发现这篇文章展示了如何创建网格以及操作:具有 CRUD 操作的 Angular 4 Grid http://www.dotnetcurry.com/angularjs/1380/angular-4-grid-crud.
看看他的代码,引起我注意的是他使用 ng-template 在编辑/查看模式之间切换的方式。
<tr *ngFor="let emp of EMPLOYEES;let i=idx">
<ng-template [ngTemplateOutlet]="loadTemplate(emp)" [ngOutletContext]="{ $implicit: emp, idx: i }"></ng-template>
</tr>
在文章中,他使用模板驱动的表单来编辑行。然而,我试图改变为反应形式。
在尝试执行此操作时,我尝试将 [(ngModel)] 替换为 formControlName,但出现了一些错误。我的第一次尝试是在表单元素内的模板 html 的开头添加 [formGroup]。但是当我尝试运行并编辑该行时,出现以下错误:
Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).
当我尝试将 [formGroup] 移动到 ng-template 内时,它可以工作,但是我无法将值绑定到字段,我必须在 loadTemplate 函数中设置值:
loadTemplate(emp: Employee) {
if (this.selemp && this.selemp.id === emp.id) {
this.rForm.setValue({
id: emp.id,
name: emp.name
});
return this.editTemplate;
} else {
return this.readOnlyTemplate;
}
}
这可以工作并以只读模式显示字段内的值:(
这里是Plunker https://plnkr.co/edit/KC8n3FN02KIhvblWztxP?p=preview到目前为止我所得到的。
如何使反应式表单与 ng-template 一起使用以及如何设置值来编辑条目?
任何帮助表示赞赏!谢谢