Check Error Count Angular Reactive Forms

Discussão em 'Angular' iniciado por Nick B, Setembro 13, 2024.

  1. Nick B

    Nick B Guest

    I want to conditionally apply a css class if the error count in a form is greater than 1. How do I do this in angular4?

    Component:

    import { Component } from "@angular/core";
    import { FormGroup, ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';

    @Component({
    ...
    })

    export class RegisterComponent {
    complexForm : FormGroup;

    constructor(fb: FormBuilder){
    this.complexForm = fb.group({
    'emailAddress' : [null, Validators.email],
    'firstName': [null, Validators.compose([Validators.required, Validators.minLength(2)])],
    ...
    })
    }

    submitForm(value: any){
    console.log(value);
    }
    }


    Template:

    <form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
    <section class="form-block">
    <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['emailAddress'].valid && complexForm.controls['emailAddress'].touched}">
    <label for="formFields_1">Email Address</label>
    <input [formControl]="complexForm.controls['emailAddress']" type="text" spellcheck="false" id="formFields_1" placeholder="" size="35">
    <span *ngIf="complexForm.controls['emailAddress'].hasError('email') && complexForm.controls['emailAddress'].touched" class="tooltip-content">
    Please enter a valid email address (ex. joan@vmware.com)
    </span>
    </div>
    <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['firstName'].valid && complexForm.controls['firstName'].touched}">
    <label for="formFields_2">First Name</label>
    <input [formControl]="complexForm.controls['firstName']" type="text" spellcheck="false" id="formFields_2" placeholder="" size="35">
    <span *ngIf="complexForm.controls['firstName'].hasError('required') && complexForm.controls['firstName'].touched" class="tooltip-content">
    Your first name must contain at least one letter
    </span>
    </div>
    </section>
    </form>


    If I want to apply the class form-error to <form> if the forms error count is greater than 1, how do I do this? Thanks for your ideas.

    Continue reading...

Compartilhe esta Página