Home > Net >  How to display an error only with the invalid email in angular
How to display an error only with the invalid email in angular

Time:05-30

I want to display an error if the user enters an invalid email. But fails. This is my code: Every time I try to add another check on the email element I get an error I have a feeling that something needs to be added to the config ts file But I do not know what

<form  [formGroup]="form" (ngSubmit)="onSubmit()">
  <div >
    <span >Welcome</span>
    <div >
      <input formControlName="email" id="email" type="email" />

      <label for="email">Email:</label>
      <span  *ngIf="form.get('email')?.invalid">
        error
      </span>
    </div>
    <div >
      <input formControlName="password" id="password" type="password" />
      <label for="password">password:</label>
    </div>
  </div>
  <div >
    <button
      type="submit"
      
      [disabled]="form.invalid"
    >
      login
    </button>
  </div>
</form>
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.scss'],
})
export class LoginPageComponent implements OnInit {
  form: FormGroup;


  ngOnInit() {`enter code here`
    this.form = new FormGroup({
      email: new FormControl(null, [Validators.required, Validators.email]),
      password: new FormControl(null, [
        Validators.required,
        Validators.minLength(6),
      ]),
    });
  }

  

  onSubmit() {}
}

What can I do?

CodePudding user response:

We should use below code for email formcontrol error check in HTML

*ngIf="form.controls['email'].errors?.required || form.controls['email'].errors?.email"

CodePudding user response:

<mat-error *ngIf="userForm.get('email').errors">
              Please Enter Valid Email
</mat-error>
  • Related