如何将required
验证程序设置为可选形式是反应形式。我有两个输入amount
和volume
。如果用户选择amount
单选按钮,则必须从volume
输入中删除所需的验证。如果为volume
,则必须从amount
app.html
<form #recForm="ngForm" name="form" [formGroup]="form" (ngSubmit)="onSubmit()">
<div>
<div class="label">
<mat-label>Charged by</mat-label>
</div>
<mat-radio-group (change)="onChargesType($event)">
<mat-radio-button
*ngFor="let charges of chargedBy; let i = index"
[checked]="i === 0"
[value]="charges"
>{{ charges }}</mat-radio-button
>
</mat-radio-group>
</div>
<mat-form-field *ngIf="!isAmount">
<input formControlName="volume" matInput placeholder="Volume" />
</mat-form-field>
<mat-form-field *ngIf="isAmount">
<input formControlName="amount" matInput placeholder="Amount" />
</mat-form-field>
</form>
app.ts
chargedBy: string[] = ['amount', 'volume'];
ngOnInit() {
this.isChargedByAmount = true;
this.form = this.fb.group({
volume: ['', []],
amount: ['', []],
});
}
onChargesType(event: MatRadioChange) {
if (event.value === 'amount') {
this.form.get('amount').setValidators(Validators.required);
this.form.get('volume').clearValidators();
this.isChargedByAmount = true;
}
if (event.value === 'volume') {
this.form.get('volume').setValidators(Validators.required);
this.form.get('amount').clearValidators();
this.isChargedByAmount = false;
}
}
答案 0 :(得分:5)
我认为这是因为您必须调用方法updateValueAndValidity()
在运行时添加或删除验证器时,必须调用updateValueAndValidity()
才能使新验证生效。
我从官方文档https://angular.io/api/forms/AbstractControl#clearValidators中找到了这个