Home > Net >  How to return angular's required name using AbstractControl
How to return angular's required name using AbstractControl

Time:08-25

in my Form im using formBuilder and i want to return a custom message, what I have to do?

this.Form = this.formBuilder.group({     
  name: ['', [Validators.required]]
});

}

And, under the input returns

The field is required

But i want to return with the name of the input, something like

The field name is required

Please someone, help me.

I'm using Angularv14.

CodePudding user response:

Here is an example of how you can show your own custom error messages, you do not need any specific param in form-control

<form >
  <mat-form-field  appearance="fill">
    <mat-label>Email</mat-label>
    <input type="email" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
           placeholder="Ex. [email protected]">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</form>

CodePudding user response:

Just put something like this inside your mat-form-field element.

<mat-error *ngIf="!form.controls['name'].valid">The field name is required</mat-error>
  • Related