【问题标题】:Angular: setErrors not working inside loopAngular:setErrors 在循环内不起作用
【发布时间】:2018-03-19 15:01:00
【问题描述】:

我有一个FormArray,我想立即验证其字段。我正在遍历 FormArray 并且对于每个元素 (FormGroup),我正在检查一个条件,禁用有效的 FormGroups 以避免用户更改它并将错误设置为特定的 FormControlFormGroup

下面是我的代码。 rowsFormArray

response.forEach((item, index) => {
    if (item.detailName.valid && item.detailNo.valid)
        (<FormArray>this.detailForm.get('rows')).at(index).disable({
            onlySelf: true
        });
    else if (!(item.detailName.valid && item.detailNo.valid))
        if (!!item.detailName.value && !item.detailNo.value)
            this.detailForm.get(['rows', index, 'detailName']).setErrors({
                'invalidValue': true
            });
        else
            this.detailForm.get(['rows', index, 'detailNo']).setErrors({
                'invalidValue': true
            });
});

错误未按预期设置。如果我 console.log 它,则该控件显示为 VALID

更新:setTimeout 包裹它,它工作了。

【问题讨论】:

  • 不知道是不是和问题有关,但是第7行的条件从来没有执行过
  • 为什么不呢?我正在检查值是否存在(不是“”)并且它有效。
  • 操作,抱歉,我用“有效”代替了“价值”

标签: angular angular2-forms angular2-formbuilder


【解决方案1】:

发生这种情况是因为您在 OnInit 挂钩中设置了验证器。当 Angular 将控件放置在视图中时,它会重新运行验证器,从而消除您设置的错误。

这里是a demo,它通过使用AfterViewInit 挂钩来解决此问题。该代码还包含在setTimeout 调用中以避免ExpressionChangedAfterChecked 错误。

我个人不同意这种行为,并且有一个open issue,所以你可以跟踪它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多