Gar*_*son 13 angular2-forms angular
我在Angular 2.1中有一个模板驱动的表单,包含许多标准控件(<input>, <select>等)和一个自定义控件,它本身包含多个输入元素.
我已经在自定义控件上实现了ControlValueAccessor,并且它正确地将它的已更改/触摸/有效值传播到父窗体.
但是..在父窗体上我有一个保存按钮,保存后我想要清除脏/触摸状态(因为这会影响应用的css),如下所示:
save(myForm: NgForm) {
myForm.form.markAsPristine();
myForm.form.markAsUntouched();
}
Run Code Online (Sandbox Code Playgroud)
这适用于顶级父窗体和自定义控件本身中的所有元素,但自定义控件中的<input>字段仍标记为触摸/脏(并且接收预先保存的样式).
是否有一种方法可以在更改脏/触摸状态时通知自定义控件,以便它可以清除它的子<input>元素以匹配?似乎如果<input>元素在自定义控件中,则不会通过在父窗体上调用markAsPristine/Untouched来更新它们.
谢谢!
Gar*_*son 11
使用活动标志的解决方法可以完成这项工作,但我也找到了另一种方法.
在父窗体上,我可以将自定义子组件作为ViewChild访问.
即以父母形式:
@ViewChild(CustomChildComponent) child1: CustomChildComponent;
Run Code Online (Sandbox Code Playgroud)
然后,当我保存在父表单中时,直接调用该子项.
save(myForm:NgForm){
save(myForm: NgForm) {
// clear anything at the parent form level
myForm.form.markAsPristine();
myForm.form.markAsUntouched();
// tell the custom component to do the same
this.child1.markAsPristineAndUntouched();
}
Run Code Online (Sandbox Code Playgroud)
}
在我定义的CustomChildComponent中的位置..
// get the input controls in the the child that we want to clear
@ViewChild('surname') surnameField: NgModel;
markAsPristineAndUntouched() {
this.surnameField.control.markAsPristine();
this.surnameField.control.markAsUntouched();
// .. clear other controls ..
}
Run Code Online (Sandbox Code Playgroud)
rob*_*xes 10
尝试添加controls['nameOfControl']这样的
myForm.form.controls['nameOfControl'].markAsPristine();
Run Code Online (Sandbox Code Playgroud)
上面的代码仅适用于表单控件.
以下似乎是一个很好的工作:
active = true;
newModel() {
this.model = new yourModel(2, '',true, '');
this.active = false;
setTimeout(() => this.active = true, 0);
}
Run Code Online (Sandbox Code Playgroud)
使用新模型重置表单并恢复'pristine'类状态.通过切换'active'标志将导致通过NgIf删除/重新添加表单.是的,这是一个小工作,直到他们可以修复:)
希望有所帮助
| 归档时间: |
|
| 查看次数: |
17328 次 |
| 最近记录: |