2

I am using following code to set error in mat form field:

<mat-form-field appearance="fill">
  <mat-label> {{ Email }}</mat-label>
  <input formControlName="email">
  <mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
  <mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}</mat-error>
</mat-form-field>

now I want to add another error when the form loads. I have a flag in ngOnInit() when it is true I want to show the error. Adding third mat-error , the error is not visible. I went through stackoverflow and tried following:

ngOnInit() {
formData.form.controls['email'].setErrors({'flag': true});
}

and adding following code in html

  <mat-form-field appearance="fill">
      <mat-label> {{ Email }}</mat-label>
      <input formControlName="email">
      <mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
      <mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}
    <mat-error *ngIf="!email.valid">{{email.errors| json}">{{ 'Display.requiredMessage' }}
</mat-error>
    </mat-form-field>

My service code is as follows:

 form: FormGroup = new FormGroup({
email: new FormControl('', [Validators.maxLength(10), Validators.required]),
});

Still not getting anything when the page loads. How can I do that?

0

4 Answers 4

2

The email form control should be marked as touched in ngOnInit, in order for the Validators to start checking the rules, as:
ngOnInit(): void { formData.form.controls['email'].markAsTouched(); }

You can read more about the FromControl properties here: https://angular.io/api/forms/AbstractControl

Sign up to request clarification or add additional context in comments.

1 Comment

It would have been much easier if you provided a stackblitz example with your code, but I've created one from the Angular Material examples: stackblitz.com/edit/angular-ren9gd, that will display an error when the component is initialized if the email is not entered. Please note that the stackblitz example runs Angular 9 and may require little tweaks. I hope it helps.
1

In your form group Validators rule, the Validators.required implies that, the user can input anything as long as it’s not an empty field, it doesn’t fail. Put Validators.email, to ensure to validate in email format
you can study and learn from this
form:

<div class="form-group">
                <mat-form-field>
                    <mat-label>{{ 'AUTH.INPUT.EMAIL' | translate }}</mat-label>
                    <input matInput type="email" placeholder="{{ 'AUTH.INPUT.EMAIL' | translate }}" formControlName="email" autocomplete="off"/>
                    <mat-error *ngIf="isControlHasError('email','required')">
                        <strong>{{ 'AUTH.VALIDATION.REQUIRED_FIELD' | translate }}</strong>
                    </mat-error>
                    <mat-error *ngIf="isControlHasError('email','email')">
                        <strong>{{ 'AUTH.VALIDATION.INVALID_FIELD' | translate }}</strong>
                    </mat-error>
                    <mat-error *ngIf="isControlHasError('email','minlength')">
                        <strong>{{ 'AUTH.VALIDATION.MIN_LENGTH_FIELD' | translate }} 3</strong>
                    </mat-error>
                    <mat-error *ngIf="isControlHasError('email','maxlength')">
                        <strong>{{ 'AUTH.VALIDATION.MAX_LENGTH_FIELD' | translate }} 320</strong>
                    </mat-error>
                </mat-form-field>
            </div>

form validator in ts file:

email: ['', Validators.compose([
                Validators.required,
                Validators.email,
                Validators.minLength(3),
                Validators.maxLength(320)
            ]),
            ],

1 Comment

@user12281262 can you post your project on stackblitz
0

try with hasError('flag') like this

<mat-error *ngIf="service.form.get('email').hasError('flag')">{{ 'Display.requiredMessage' }}

Comments

0

A solution that works for me:

In the ts file

public checkoutForm = this._FormBuilder.group({
   control: ['', Validators.required],
});
get f() { return this.checkoutForm.controls; }

In the HTML file

<mat-label>mon label <span *ngIf="f.control.errors && f.control.errors.required" class="color-red">*</span></mat-label>

I just tested this solution by chance because I show errors the same way. This code will display the asterisk as long as the field is not filled.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.