gpt4 book ai didi

Angular 2 Formbuilder条件验证输入

转载 作者:行者123 更新时间:2023-12-02 14:11:08 25 4
gpt4 key购买 nike

我正在使用 Angular 2 formbuilder 创建一个表单,我想根据单选框输入更改有条件地验证输入字段。当我单击百分比单选框时,应验证百分比输入。当我单击金额单选框时,它应该验证金额输入字段。

HTML 代码

(我正在使用 Material 输入组件)

<md-radio-group formControlName="splitType" (click)="splitTypeClicked()">
<md-radio-button value="amount">Amount</md-radio-button>
<md-radio-button value="percentage">Percentage</md-radio-button>
</md-radio-group>

<input mdInput placeholder="Amount" formControlName="amount" >
<input mdInput placeholder="Percentage" formControlName="percentage" >

Angular 2 组件

constructor(private fb: FormBuilder){}

ngOnInit() {

this.splitChargeForm = this.fb.group({
splitType: ['', Validators.required],
amount: [''], //validate when splitType = amount
percentage: [''] //validate when splitType = percentage

});

最佳答案

将此代码写入 ngOnInit() 方法。这有帮助吗

解决方案 1:

 this.splitChargeForm.get('splitType')
.valueChanges.subscribe((value: string) => {
if (value === 'amount') {
this.splitChargeForm.get('amount').setValidators(Validators.required);
this.splitChargeForm.get('percentage').clearValidators()
} else {
this.splitChargeForm.get('percentage').setValidators(Validators.required);
this.splitChargeForm.get('amount').clearValidators()
}
});

解决方案 2:

//表单生成器

  this.splitChargeForm = this.fb.group({
splitType: ['', Validators.required],
amount: [{value: '', disabled: false}, Validators.required],
percentage: [{value: '', disabled: true}, Validators.required]
});

//启用和禁用输入(写在onInit()方法或构造函数中)

this.splitChargeForm.get('splitType')
.valueChanges.subscribe((value: string) => {
if (value === 'amount') {
this.splitChargeForm.get('amount').enable;
this.splitChargeForm.get('percentage').disable();
} else {
this.splitChargeForm.get('percentage').enable();
this.splitChargeForm.get('amount').disable()
}
});

Html 应该是这样的

<md-radio-group formControlName="splitType" (click)="splitTypeClicked()">
<md-radio-button value="amount">Amount</md-radio-button>
<md-radio-button value="percentage">Percentage</md-radio-button>
</md-radio-group>

<input mdInput placeholder="Amount" formControlName="amount" *ngIf="splitChargeForm.value.splitType === 'amount" >
<input mdInput placeholder="Percentage" formControlName="percentage" *ngIf="splitChargeForm.value.splitType === 'percentage" >

关于Angular 2 Formbuilder条件验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com