Search code examples
angularangular-reactive-formsangular-forms

angular 2 how to set initial error state on form controls


When my html renders in Angular 2 how do I set all form controls to their error state if they are in error? To clarify in this sample code there is only one drop down. When the form loads it is non red / no required message. If I open the drop down and then click outside somewhere without making any selection THEN the red magic happens and I see the error message. I need it to be in error state/red with error message when the form renders for the first time. I guess I need to set error state on that control somewhere. Just don't know where and how. Please advise. Code is below https://stackblitz.com/edit/angular-error-initial


Solution

  • Programmatically set your control as touched by calling markAsTouched() in ngAfterViewInit

    ngAfterViewInit(){
        this.animalControl.markAsTouched();
      }
    

    Stackblitz

    https://stackblitz.com/edit/angular-error-initial-atr11t?embed=1&file=app/select-hint-error-example.ts