【发布时间】:2017-08-17 18:29:27
【问题描述】:
我刚开始使用 Angular 4,我需要开发一个 CRUD 网格,用户可以在其中添加、编辑或删除行。
在我的研究过程中,我发现这篇文章展示了如何创建网格以及操作:Angular 4 Grid with CRUD operations。
查看他的代码,引起我注意的是他使用 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).
当我尝试在 ng-template 中移动 [formGroup] 时,它可以工作,但是我无法将值绑定到字段,我必须在 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。
如何使反应式表单与 ng-template 一起使用以及如何设置值以编辑条目?
感谢任何帮助!谢谢
【问题讨论】:
-
我删除并取消删除了我的答案,所以你不会收到通知,所以我在这里告诉它:) 重新考虑你的代码,正如你从我的回答中看到的那样,这对性能造成了很大的伤害。
标签: javascript angular templates