【问题标题】:Setting formControl in Angular 2 with boolean value 'true' programmatically is marking form as dirty以编程方式在 Angular 2 中使用布尔值“true”设置 formControl 将表单标记为脏
【发布时间】:2017-12-12 15:03:46
【问题描述】:

我正在尝试以编程方式在 formControl 中设置布尔值。但这是将表单标记为脏。根据 Angular 文档,“对控件值的编程更改不会将其标记为脏” https://angular.io/api/forms/AbstractControl#pristine

代码:

this.formGroup.get(ruleOutput.attributeKey).setValue(JSONUtils.parseJSON(ruleOutput.attributeValue))

仅供参考,JSONParser 代码(不要认为这里有任何错误):

public static parseJSON(input : any) : any{
    try{
        return JSON.parse(input);
    }catch(Error){
        console.log("Inside JSON Utils: Error while parsing input JSON :");
        console.log(input);
        console.log(Error.toString());
        console.log("Return Empty JSON");
        return JSON.parse("{}");
    }
}

点在设置值后,表单被标记为脏。

请帮助我找到问题的根本原因。

【问题讨论】:

  • if (ruleDataList && ruleDataList.length > 0) { ruleDataList[0].ruleOutputList.forEach( ruleOutput => { if (DisplayUtils.isKeyDisplayable(ruleOutput.attributeKey, "*")) { this. formGroup.get(ruleOutput.attributeKey).setValue(JSONUtils.parseJSON(ruleOutput.attributeValue)); this.formGroup.get(ruleOutput.attributeKey).markAsPristine; } } ) this.ruleDataAlreadyExists = true; }
  • 请为此创建一个演示,我不明白为什么会发生这种情况。

标签: angular angular-reactive-forms


【解决方案1】:

这仅适用于getters,不适用于setters。如果您查看setValue 的源代码,您会看到它也进行了验证,因此将控件标记为脏,因为它已被更改:

https://github.com/angular/angular/blob/5.1.0/packages/forms/src/model.ts#L744

你可以做的是,设置表单值,然后调用myFrom.markAsPristine()

【讨论】:

  • 是的,现在,我明确添加了 markAsPristine()。另一件事是它只发生在“布尔”,而不是其他数据类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2018-03-19
  • 2013-06-22
  • 2015-08-27
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多