首页 > 解决方案 > Angular4反应式表单验证不起作用

问题描述

在 pic1 我写了一个输入标签(行:101)和另一个从其他地方复制的输入标签(行:102)但是第一个输入标签正在工作,但不是第二个,因为对于第二个输入标签没有“ng-invalid ng -touched” DOM 中的类(图 2)。 1 图2

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";
@Component({
 selector: "app-sign-up",
 templateUrl: "./sign-up.component.html",
 styleUrls: ["./sign-up.component.css"]
})
export class SignUpComponent implements OnInit {
ngOnInit(): void {
//this.Registration.va
}
Registration = new FormGroup({
  fullName: new FormControl("",[Validators.required])
 });
}

标签: angularangular4-formsreactive-forms

解决方案


问题是您对两个不同的输入使用相同的控件。每个表单域都必须有单独的 FormControl。

进行以下更改

signUpComponent.component.ts

Registration = new FormGroup({
 fullName1: new FormControl("",[Validators.required]),
 fullName2: new FormControl("",[Validators.required])
})

在您的 .html 文件中

<input formControlName="fullName1" id="fullName1" />
<input formControlName="fullName2" id="fullName2" />

推荐阅读