0

我是新手Angular Material。我正在使用Angular Material (8). 这样做时,我看到重新加载页面时显示错误消息(通过点击浏览器上的“刷新”按钮)。从未以任何方式、形状或形式触及该领域。

在此处输入图像描述

为什么会这样?

TIA

文件:register.component.html

[ ... snip ...]

       <div class="flex-register-form">

            <!-- Form -->
            <form [formGroup]="registerForm" (ngSubmit)="registerForm.valid && onSubmit()" class="text-center">

                <div class="form-col">
                    <div class="col">
                        <!-- First name -->
                        <div class="md-form">
                            <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                                formControlName="firstname" />
                            <label for="materialRegisterFormFirstName">First name</label>
                            <mat-error *ngIf="registerForm.controls['firstname'].hasError('required')" >First name is required</mat-error>
                        </div>

[ ... snip ...]

文件:register.component.ts

import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import {  FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  user: RegisterModel = new RegisterModel();
  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.registerForm = new FormGroup({
      'firstname': new FormControl(null, [Validators.required]),
      'lastname': new FormControl(null, [Validators.required, Validators.maxLength(25)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.maxLength(25)]),
      'password': new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree': new FormControl(null, [Validators.required])
    });
  }

  onSubmit() {
    console.log(" was submited ");
  }

}
4

1 回答 1

1

这是因为根据验证它正在等待。touched但是,我们还没有接触到控件,所以我们可以做的是,我们可以通过检查表单域的控件状态来检查用户是否与控件进行了交互。

更正

<mat-error *ngIf="registerForm.controls['firstname'].hasError('required') && registerForm.controls.firstname.touched" >First name is required</mat-error>

你可以在这里阅读更多关于它的信息

于 2020-02-14T09:30:17.007 回答