如果用户输入密码1234,那么我只想显示错误消息,那么仅确认密码是必填项。
正常验证工作正常。视图中仅不显示相关的验证。
如果我调试其显示形式无效,但是我无法在HTML页面中显示消息
我的html页面
<div class="container">
<h2>Reactive Form</h2>
<form [formGroup]="contFrm" (ngSubmit)="submitContFrm()">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" formControlName="email" [ngClass]="{'is-invalid': submited && f.email.errors}">
<div *ngIf="f.email.touched && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">
Email is Requird.
</div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" formControlName="password" [ngClass]="{'is-invalid': submited && f.password.errors}">
<div *ngIf="submited && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">
Password is Requird.
</div>
</div>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" formControlName="cpassword">
<div *ngIf="submited && f.cpassword.errors" class="invalid-feedback">
<div *ngIf="f.cpassword.errors.required">
Password is Requird.
</div>
</div>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
contFrm: FormGroup;
submited = false;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.contFrm = this.fb.group({
email: ['', Validators.required],
password: ['', Validators.required],
cpassword: ['']
});
this.contFrm.get('password').valueChanges.subscribe(
(data) => this.confirmPassword(data)
)
}
get f() {
return this.contFrm.controls;
}
submitContFrm() {
this.submited = true;
if(this.contFrm.invalid) {
return;
}
}
confirmPassword(data) {
let cpwd = this.contFrm.get('cpassword');
if(data == "1234") {
cpwd.clearValidators();
cpwd.setValidators([Validators.required]);
} else {
cpwd.clearValidators();
}
cpwd.updateValueAndValidity();
}
}
请帮帮我
答案 0 :(得分:0)
updateValueAndValidity()不会递归更新后代的值和有效性,它只会更新祖先的值和有效性,因此修改您的代码并检查
confirmPassword(data) {
let cpwd = this.contFrm.get('cpassword');
if(data == "1234") {
cpwd.clearValidators();
cpwd.setValidators([Validators.required]);
} else {
cpwd.clearValidators();
}
this.contFrm.updateValueAndValidity();
}
}