Saajan Singh
Saajan Singh

Reputation: 191

Setting formControl in Angular 2 with boolean value 'true' programmatically is marking form as dirty

I am trying to set boolean value in formControl programmatically. But this is marking form as dirty. Going by Angular docs, "programmatic changes to a control's value will not mark it dirty" https://angular.io/api/forms/AbstractControl#pristine

Code:

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

FOR FYI, JSONParser Code (Don't think any error here):

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("{}");
    }
}

Point is after setting the value, form is being marked as dirty.

Please help me in getting to root cause of this.

Upvotes: 0

Views: 3180

Answers (1)

Sonu Kapoor
Sonu Kapoor

Reputation: 1637

This is only true for getters, not setters. If you look at the source-code of setValue, you will see that it does the validation as well and therefore marks the control as dirty, since it has been changed:

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

What you could do is maybe, set the form values, and then call myFrom.markAsPristine().

Upvotes: 1

Related Questions