0

我从一个运行良好的旧项目中借用了以下代码。但是现在它没有显示任何错误消息,因为我在新项目中使用了相同的代码。

HTML

<mat-card class="centered card">
<form [formGroup]="loginForm"> 
    <mat-form-field appearance='outline'>
        <mat-label>Email</mat-label>
        <input matInput fromControlName="email" type="email" placeholder="Email"/>
        <mat-error>
            <div *ngIf="loginForm.get('email').hasError('pattern')">Enter valid Email ID</div>
            <div *ngIf="loginForm.get('email').hasError('required')">Email is required</div>
        </mat-error>
    </mat-form-field>
    <br>
    <mat-form-field appearance='outline'>
        <mat-label>Password</mat-label>
        <input matInput fromControlName="pass" type="pass" placeholder="Password"/>
        <mat-error>
            <div *ngIf="loginForm.get('pass').hasError('required')">Password is required</div>
        </mat-error>
    </mat-form-field>
    <br>
    <mat-card-actions>
        <button mat-raised-button class="full-width" (click)="auth()">Login</button>
    </mat-card-actions>
</form>
</mat-card>

打字稿

import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

    loginForm: FormGroup;
    userEmail: FormControl;
    userPass: FormControl;

    constructor() { }

    ngOnInit() {
      this.userEmail = new FormControl('', Validators.compose(
          [Validators.required, Validators.pattern(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,63})$/)]
      ));
      this.userPass = new FormControl('', Validators.required);
      this.loginForm = new FormGroup({
        email: this.userEmail,
        pass: this.userPass
      });
    }

    auth(event){
      console.log(event);
    }

}

该代码以前可以按预期工作。我想针对不同的验证失败情况显示不同的消息。

4

1 回答 1

0

这似乎是一个简单的错字:而不是fromControlName, 将其更改为formControlName

于 2020-05-18T16:50:45.117 回答