Search code examples
angularangular-forms

Explicitly validate Template Driven forms in Angular


I have a template driven form which fills controls if data is available. But after the controls are filled, the error styles are not applied while validation(using Angular material elements). Error styles are applied only if I touch element or submit form. How can I trigger form validation manually ?
You can check stackblitz: https://stackblitz.com/github/vugar005/Angular-NT-Components/tree/template-driven-approach
Thanks in advance


Solution

  • Trigger markAsTouched() method explicitly, if there is an error on input control during page load

    getErrors(str) {
    if (this.ntForm && this.ntForm.controls[str] ) {
      const control = this.ntForm.controls[str];
      const errors = control.errors; 
      if (!errors) { return; }      
      control.markAsTouched();
      // remaining code
    }