How do I know when custom form control is marked as pristine in Angular?

My workaround is inspired by Slava's post and Get access to FormControl from the custom form component in Angular, and mixing template forms (ngModel) and reactive forms together. The checkbox control inside the component reflects dirty/pristine state and reports its state back outside to form group. So I can apply styles to checkbox input (<label>) control based on classes ng-dirty, ng-valid etc. I have not implemented markAsTouched, markAsUntouched as it can be done in similar way. Working demo on StackBlitz

The example component code is:

import { AfterViewInit, Component, Input, OnInit, Optional, Self, ViewChild } from "@angular/core";
import { ControlValueAccessor, NgControl, NgModel } from "@angular/forms";

@Component({
  selector: "app-custom-checkbox-control",
  template: '<input id="checkBoxInput"\
  #checkBoxNgModel="ngModel"\
  type="checkbox"\
  name="chkbxname"\
  [ngModel]="isChecked"\
  (ngModelChange)="checkboxChange($event)"\
>\
<label for="checkBoxInput">\
{{description}}\
</label>\
<div>checkbox dirty state: {{checkBoxNgModel.dirty}}</div>\
<div>checkbox pristine state: {{checkBoxNgModel.pristine}}</div>',
  styleUrls: ["./custom-checkbox-control.component.css"]
})
export class CustomCheckboxControlComponent
  implements OnInit, AfterViewInit,  ControlValueAccessor {
  disabled: boolean = false;
  isChecked: boolean = false;
 
  @Input() description: string;
  @ViewChild('checkBoxNgModel') checkBoxChild: NgModel;

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (this.ngControl != null) {
      this.ngControl.valueAccessor = this;
    }
  }

  checkboxChange(chk: boolean) {
    console.log("in checkbox component: Checkbox changing value to: ", chk);
    this.isChecked = chk;
    this.onChange(chk);

  }
  ngOnInit() {}

  ngAfterViewInit(): void {
    debugger
    this.checkBoxChild.control.setValidators(this.ngControl.control.validator);

    const origFuncDirty = this.ngControl.control.markAsDirty;
    this.ngControl.control.markAsDirty = () => {
      origFuncDirty.apply(this.ngControl.control, arguments);
      this.checkBoxChild.control.markAsDirty();
      console.log('in checkbox component: Checkbox marked as dirty!');
    }

    const origFuncPristine = this.ngControl.control.markAsPristine;
    this.ngControl.control.markAsPristine = () => {
      origFuncPristine.apply(this.ngControl.control, arguments);
      this.checkBoxChild.control.markAsPristine();
      console.log('in checkbox component: Checkbox marked as pristine!');
    }

  }


  //ControlValueAccessor implementations

  writeValue(check: boolean): void {
    this.isChecked = check;
  }

  onChange = (val: any) => {};

  onTouched = () => {};

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}

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:

Monkey-patching the 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 origFunc = this.control.markAsPristine;
    this.control.markAsPristine = function() {
      origFunc.apply(this, arguments);
      console.log('Marked as pristine!');
    }
  }

}

Watching for changes with ngDoCheck

Be 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.