在我们的Angular 4 app中,我们有一个
<parent-component>
,其中包含<form>
<form>
有<level-1-child>
<level-1-child>
有<level-2-child>
<level-2-child>
有<textarea>
我们需要做什么?
<form>
,<parent-component>
&amp;的<level-1-child>
个元素。 <level-2-child>
点击或提交<button>
的{{1}} <parent-component>
<form>
看起来像这样:
<parent-component>
<form [formGroup]="myGroup" #f="ngForm" name="parent-component" (submit)="resetForm(f)" >
<input name="abc" id="abc" formControlName="abc">
<level-1-child [formGroup]="myGroup"></level-1-child>
<input type="submit" value="Reset form">
</form>
看起来像这样:
<level-1-child>
<input name="abc" id="abc" formControlName="abc">
<level-2-child [formGroup]="myGroup">
</level-2-child>
看起来像这样:
<level-2-child>
<div [formGroup]="myGroup">
<textarea formControlName="abc" id="abc" name="abc" [(ngModel)]="level-2-child.txt" >
</textarea>
</div>
,parent-component.ts
&amp;的代码level-1-child.ts
位于以下行:
level-2-child.ts
此代码仅重置
import { Component, OnInit } from '@angular/core'; import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms'; @Component({ moduleId: module.id, selector: 'parent-component', //level-1-child, level-2-child templateUrl: 'parent-component.html' //level-1-child, level-2-child }) export class ParentComponent { //Level1Child, Level2Child myGroup = new FormGroup({abc: new FormControl()}); }
的{{1}}。有什么办法解决这个问题?
尝试解决方案1
根据@StepanZarubin的suggestion,input#abc
是这样的:
<parent-component>
使用模板parent-component.ts
,如下所示:
resetForm(f) {
f.resetForm();
}
<parent-component>
的模板是:
<form #f="ngForm" (submit)="resetForm(f)" >
<level-1-child>
<level-2-child>
<level-3-child>
...
<level-n-child>
</level-n-child>
...
</level-3-child>
</level-2-child>
</level-1-child>
<button type="submit"> Submit </button>
</form>
但由于某些原因,这并未重置<level-n-child>
的{{1}}元素。
尝试解决方案2
尝试解决方案3
[parentFormGroup]
导致错误:无法绑定到'parentFormGroup',因为它不是'level-n-child'的已知属性
尝试使用REACTIVE_FORM_DIRECTIVES
解决此错误时会抛出另一个错误:
[ts]模块'“node_modules / @ angular / forms / forms”'没有导出成员'REACTIVE_FORM_DIRECTIVES'。
然而,we're already using the latest并不是主要问题。
尝试解决方案4
尝试过解决方案5
可能的解决方案
我们不希望在这些组件上输入大量凌乱的输入/输出代码。
我们可以使用共享服务这样的方法吗?
答案 0 :(得分:2)
要使用“空”数据初始化表单,我会执行以下操作:
initializeProduct(): IProduct {
// Return an initialized object
return {
id: 0,
productName: null,
productCode: null,
tags: [''],
releaseDate: null,
price: null,
description: null,
starRating: null,
imageUrl: null
};
}
然后绑定到初始化的产品。
您可以在此处找到完整示例:Observable class itself(特别是APM文件夹)。
此代码适用于我在Pluralsight上的“Angular Reactive Forms”课程,如果您想了解有关其构建方式的更多详细信息:https://github.com/DeborahK/Angular2-ReactiveForms