Search code examples
angulartypescriptangular-ng-if

How to move conditional error checks from NgIf to typescript file?


In my Angular app, I need to add/remove CSS classes based on whether or not a FormControl has been touched, is dirty, is invalid, etc.

I'm using the ngClass directive to do this:

<div class="form-group has-required"
    [ngClass]="{'has-error':
        (conditionsForm.get('acceptTerms').touched || conditionsForm.get('acceptTerms').dirty)
         && conditionsForm.get('acceptTerms').errors}">
</div

Here is what I have in my Typescript currently:

ngOnInit() {
    this.conditionsForm = this.fb.group({
        acceptTerms: new FormControl('', Validators.required),
        insuredType: new FormControl('', Validators.required),
        reportInjury: new FormControl('', Validators.required)
    });
}

As the above conditional is quite long, I would like to move it into my Typescript file.

Is there a particular method to doing this? I'm not sure how I can do it. Can someone please tell me what my approach should be?

Thanks a lot in advance!


Solution

  • I would go with this which will work for all formControls:

    public hasError(formControlName: string): boolean {
     if (this.user.get(formControlName).errors) {
      return true;
     }
     else {
      return false;
     }
    }
    

    HTML Code:

    <div [ngClass]="{'has-error': hasError('acceptTerms')}">
    // Other HTML
    </div>
    

    So in case of other form controls you can easily use it as:

    <div [ngClass]="{'has-error': hasError('another_formcontrol')}">
     //
    </div>
    

    Working_Demo