在我们的 Angular 4 app , 我们有一个
-
<parent-component>
它有一个<form>
<form>
有<level-1-child>
<level-1-child>
有<level-2-child>
<level-2-child>
有<textarea>
我们需要做什么?
- 重置
<form>
<parent-component>
的元素,<level-1-child>
&<level-2-child>
在<button>
单击或提交<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
的代码, 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()});
}
This code is only resetting the
input#abc
of<parent-component>
. What is the fix for this?
到目前为止我们尝试了什么?
尝试过的解决方案 1
根据 @StepanZarubin的 suggestion , 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>
的模板是:
<input name="inp" id="inp" #inpField="ngModel" [(ngModel)]="childModel.inp">
但是由于某些原因,这并没有重置 input#inp
<level-n-child>
的元素.
尝试过的解决方案2
已尝试解决方案 3
- 使用stuff like
[parentFormGroup]
导致错误:
Can't bind to 'parentFormGroup' since it isn't a known property of 'level-n-child'
当尝试使用 REACTIVE_FORM_DIRECTIVES
解决此错误时抛出另一个错误:
[ts] Module '"node_modules/@angular/forms/forms"' has no exported member 'REACTIVE_FORM_DIRECTIVES'.
然而,we're already using the latest这不是主要问题。
尝试过的解决方案 4
尝试解决方案 5
可能的解决方案
- > @PaulParton正在谈论 form group ,我们不确定这是否是正确的解决方案。
我们不希望在这些组件上放置大量用于输入/输出的困惑代码。
有没有办法为此使用共享服务之类的东西?
最佳答案
要用“空”数据初始化表单,我会这样做:
initializeProduct(): IProduct {
// Return an initialized object
return {
id: 0,
productName: null,
productCode: null,
tags: [''],
releaseDate: null,
price: null,
description: null,
starRating: null,
imageUrl: null
};
}
然后绑定(bind)到初始化的产品上。
您可以在此处找到完整示例:https://github.com/DeborahK/Angular2-ReactiveForms (特别是 APM 文件夹)。
此代码适用于我在 Pluralsight 上的“Angular Reactive Forms”类(class),如果您想查看有关其构建方式的更多详细信息:https://app.pluralsight.com/library/courses/angular-2-reactive-forms/table-of-contents
关于javascript - 单击父按钮单击时如何重置子输入的数据和 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44597080/