handling with multiple mat-errors

Discussão em 'Angular' iniciado por Arter, Fevereiro 19, 2025.

  1. Arter

    Arter Guest

    I have my error handling for mat-input like this

    <mat-form-field>
    <input formControlName="title" matInput placeholder="Title*" />
    <mat-error *ngIf="addNewForm.get('title').errors?.required">
    Can not be empty
    </mat-error>
    <mat-error *ngIf="addNewForm.get('title').errors?.minlength">
    Min length is 1 character
    </mat-error>
    <mat-error *ngIf="addNewForm.get('title').errors?.maxlength">
    Max length is 255 characters
    </mat-error>
    </mat-form-field>

    <mat-form-field>
    <input formControlName="name" matInput placeholder="Name*" />
    <mat-error *ngIf="addNewForm.get('name').errors?.required">
    Can not be empty
    </mat-error>
    <mat-error *ngIf="addNewForm.get('name').errors?.minlength">
    Min length is 1 character
    </mat-error>
    <mat-error *ngIf="addNewForm.get('name').errors?.maxlength">
    Max length is 255 characters
    </mat-error>
    </mat-form-field>


    How to handle this directly in component, soo instead of writing all of this errors manually, check all in component and dynamically set errors, something like this

    <mat-form-field>
    <input formControlName="title" matInput placeholder="Title*" />
    <mat-error>{{ someError }}</mat-error>
    </mat-form-field>

    <mat-form-field>
    <input formControlName="name" matInput placeholder="Name*" />
    <mat-error>{{ someError }}</mat-error>
    </mat-form-field>


    Here is component

    this.addNewUserForm = this.formBuilder.group({
    title: [
    "",
    [
    Validators.required,
    Validators.minLength(1),
    Validators.maxLength(255),
    noWhitespaceValidator
    ]
    ],
    name: [
    "",
    [
    Validators.required,
    Validators.minLength(4),
    Validators.maxLength(255),
    noWhitespaceValidator
    ]
    ]
    });

    Continue reading...

Compartilhe esta Página