I have several custom form control components in my Angular application, which implement ControlValueAccessor interface and it works great.
However, whe
After thorough investigation I've found out that this functionality is not specifically provided by Angular. I've posted an issue in the official repository regarding this and it's gained feature request status. I hope it will be implemented in near future.
Until then, here's two possible workarounds:
markAsPristine()@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: MyCustomFormComponent,
multi: true
}]
})
export class MyCustomFormComponent implements ControlValueAccessor, OnInit {
private control: AbstractControl;
ngOnInit () {
const self = this;
const origFunc = this.control.markAsPristine;
this.control.markAsPristine = function () {
origFunc.apply(this, arguments);
console.log('Marked as pristine!');
}
}
}
ngDoCheckBe advised, that this solution could be less performant, but it gives you better flexibility, because you can monitor when pristine state is changed. In the solution above, you will be notified only when markAsPristine() is called.
@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: MyCustomFormComponent,
multi: true
}]
})
export class MyCustomFormComponent implements ControlValueAccessor, DoCheck {
private control: AbstractControl;
private pristine = true;
ngDoCheck (): void {
if (this.pristine !== this.control.pristine) {
this.pristine = this.control.pristine;
if (this.pristine) {
console.log('Marked as pristine!');
}
}
}
}
And if you need to access the FormControl instance from your component, please see this question: Get access to FormControl from the custom form component in Angular.