如何在不影响其功能的情况下在表单数组中添加无效的表单控件 [英] How can I add a invalid Form Control in a Form Array without compromise its funcionality

查看:30
本文介绍了如何在不影响其功能的情况下在表单数组中添加无效的表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个动态表单,将表单控件(一种必需的表单控件)添加到表单数组中.

I want to create a dynamic form which add Form Controls (a required form control) to a Form Array.

表单控件无效,需要用户填写(空白)

The Form Control is invalid because it needs to be filled by the user (it is blank)

但是当我添加表单控件时,出现错误

But when I add the form control, I get an error

ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改.以前的值:'ng-valid:true'.当前值:'ng-valid:false'

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-valid: true'. Current value: 'ng-valid:false'

在控制台中.

add(formControl) {
    (this.formGroup.get('array') asFormArray).push(formControl)
}

推荐答案

您只需要在添加无效子表单后手动调用更改检测即可.变更检测自上而下工作.根据该错误判断,当单击按钮(或您用来添加新表单的任何东西)更改检测周期运行时,它已经在到达新添加的无效子表单时检查了表单有效性.在添加新表单后手动调用它会告诉 Angular 将需要第二个更改检测周期,因为更高级别元素中的表达式很可能已更改.

You just need to manually call change detection after adding the invalid child form. Change detection works top-down. And judging by that error, when the button click's (or whatever you're using to add the new form's) change detection cycle runs, it has already checked the form validity by the time it gets to your newly added invalid child form. Manually calling it after the adding the new form tells Angular that a second change detection cycle will be needed because an expression in a higher up element has most likely changed.

constructor(private readonly cdr: ChangeDetectorRef) {}

add(formControl) {
  (this.formGroup.get('array') asFormArray).push(formControl);
  this.cdr.detectChanges();
}

这篇关于如何在不影响其功能的情况下在表单数组中添加无效的表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆