<div class="p-field-checkbox">
<p-checkbox formControlName="passwordUpdate" binary="false" name="passwordUpdate" inputId="passwordUpdate"></p-checkbox>
<label for="passwordUpdate">Update Password</label>
</div>
<div class="input-group" *ngIf="form.get('passwordUpdate').value">
<label class="required" for="password">Password</label>
<input formControlName="password" type="password" name="password" placeholder="Password" id="password" class="input input-m" [required]="form.get('passwordUpdate').value">
</div>
如果条件为“true”,则会出现密码字段。单击提交按钮后,将验证密码字段是否为必填字段。
然后条件变为“假”,但所需的验证未删除,因此无法提交表单。请帮我解决这个问题。提前致谢。
最佳答案
当您使用 ReactiveForms 时,我们可以根据“passwordUpdate”的状态添加和删除验证
<form [formGroup]="contactForm">
<div>
<label>Update Password</label>
<input type="checkbox" formControlName="resetPassword" (change)="onCheckboxChange()" />
</div>
<div *ngIf="contactForm.get('resetPassword')?.value">
<label for="last-name">Password: </label>
<input type="text" formControlName="password">
Required: {{ contactForm.get('password')?.hasError('required') }}
</div>
<div>
<button type="submit">Submit</button>
Valid Form : {{ contactForm.valid }}
</div>
</form>
我添加了“更改”函数,该函数会触发 .ts 文件中的一个函数,该函数会重置“密码”字段的验证。
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
contactForm!: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.createContactForm();
}
createContactForm() {
this.contactForm = this.formBuilder.group({
resetPassword: [],
password: [],
});
}
onCheckboxChange(): void {
if (this.contactForm.controls['resetPassword'].value) {
this.contactForm.get('password')?.setValidators([Validators.required]);
this.contactForm.get('password')?.updateValueAndValidity();
} else {
this.contactForm.controls['password'].clearValidators();
this.contactForm.get('password')?.updateValueAndValidity();
}
}
}
我在 stackblitz 上创建了一个相同的模拟项目。请检查以供引用。
关于angular - 如何在 Angular 中一起使用 *ngIf 和条件要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69466441/