我正在使用带有表单验证的角度反应式表单。我想创建一个选择输入,并且只有选择特定的选项('其他')我想显示其他文本输入(因此用户可以输入自定义答案)。我默认情况下不需要输入文本,然后onValueChanged
我正在检查选项是否为“其他”并用于setValidators
将输入更改为必需。这似乎可行,但我收到此错误:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.
这是我的代码:
组件.ts
buildForm() {
this.validationForm = this.formBuilder.group({
PaymentMethod: this.formBuilder.control(null, [Validators.required]),
Package: this.formBuilder.control(null, [Validators.required]),
CustomAmount: this.formBuilder.control(null, [Validators.min(50), Validators.max(400)]),
});
this.validationForm.valueChanges
.subscribe((data) => this.onValueChanged(data));
this.onValueChanged(); // (re)set validation messages now
}
onValueChanged(data?: any) {
if (data && data.Package && data.Package.Name === 'Other') {
console.log('amount should be required now');
this.validationForm.controls.CustomAmount.setValidators([Validators.min(50), Validators.max(400), Validators.required]);
}else {
this.validationForm.controls.CustomAmount.setValidators([Validators.min(50), Validators.max(400)]);
}
...
}
组件.html
<form [formGroup]="validationForm" (ngSubmit)="onSubmit()" novalidate>
<div class="form-group">
<p>
<strong style="display: inline-block; width: 120px;">Payment Method</strong>
<md-radio-group class="md-radio-group-spacing" formControlName="PaymentMethod" [(ngModel)]="radio.group1">
<md-radio-button value="Cash">Cash</md-radio-button>
<md-radio-button value="Credit">Credit</md-radio-button>
</md-radio-group>
</p>
<p>
<md-select *ngIf="packages" placeholder="Choose Package" formControlName="Package" [(ngModel)]="selectedPackage">
<md-option *ngFor="let package of packages" [value]="package">
{{ package.Name }} <span class="blue-500"> {{ package.Price | currency:'USD':true }}</span>
</md-option>
</md-select>
</p>
<div *ngIf="selectedPackage" class="callout callout-info">
<strong>Selected:</strong> {{selectedPackage.Name}}
<p>{{selectedPackage.Description}}</p>
</div>
<div *ngIf="selectedPackage && selectedPackage.Name == 'Other'">
<div class="form-group">
<md-input-container class="full-width">
<input type="number" mdInput formControlName="CustomAmount" placeholder="Enter Amount">
</md-input-container>
<small *ngIf="formErrors.CustomAmount" class="red-500">
{{ formErrors.CustomAmount }}
</small>
</div>
</div>
</div>
<button md-raised-button type="submit" class="btn-w-md" color="primary" [disabled]="!validationForm.valid">Submit</button>
<span class="space space-md"></span>
<button md-raised-button type="button" class="btn-w-md" (click)="dialogRef.close('Cancel')">Cancel</button>
</form>
编辑 我在这里找到了一个启用/禁用输入的解决方案。效果很好!但我仍然很高兴听到您认为最好的想法和其他解决方案。谢谢