如何将required
验证器设置为可选是反应形式。我有两个输入amount
和volume
. 如果用户选择amount
单选按钮,则必须从输入中删除所需的验证。volume
如果volume
,则必须从amount
应用程序.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>
应用程序.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;
}
}