How do we do that? There was $setPristine()
in ng1. Btw, I'm talking about ControlGroup
type of form.
"pristine" means the user hasn't changed the value since it was displayed in this form. So given a user has an autocomplete input that looks up airports nearby, when the user selects an option then we set the value of the FormControl to the selected option.
markAsPristine() takes an opts argument; markAsPristine(opts: { onlySelf?: boolean; } = {}) . When the onlySelf value is false (which is the default value )), the control and all its direct ancestors are marked as pristine. If onlySelf is true; only the control itself is marked as pristine.
pristine: This property returns true if the element's contents have not been changed. dirty: This property returns true if the element's contents have been changed. untouched: This property returns true if the user has not visited the element. touched: This property returns true if the user has visited the element.
There is the markAsPristine
method (it seems undocumented for now, but can be found here: https://github.com/angular/angular/blob/53f0c2206df6a5f8ee03d611a7563ca1a78cc82d/tools/public_api_guard/forms/index.d.ts#L42).
Basically, this.form.markAsPristine()
does what you expect.
update
In the new forms module this was improved a lot.
AbstractControl
, the base class of most form classes provides
markAsTouched({onlySelf}?: {onlySelf?: boolean}) : void markAsUntouched({onlySelf}?: {onlySelf?: boolean}) : void markAsDirty({onlySelf}?: {onlySelf?: boolean}) : void markAsPristine({onlySelf}?: {onlySelf?: boolean}) : void markAsPending({onlySelf}?: {onlySelf?: boolean}) : void
And several other new methods
disable({onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void enable({onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void
setValue(value: any, options?: Object) : void patchValue(value: any, options?: Object) : void
reset(value?: any, options?: Object) : void updateValueAndValidity({onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void // (old) setErrors(errors: {[key: string]: any}, {emitEvent}?: {emitEvent?: boolean}) : void
original
That's currently not supported. See https://github.com/angular/angular/issues/5568 and https://github.com/angular/angular/issues/4933. The usual workaround is to re-create the form to get a pristine one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With