angular - 根据选择值禁用 Angular Reactive 表单输入
问题描述
我有一个表单(使用 Angular Material),我想根据选择值禁用一些输入字段。我的代码如下所示:
HTML
<mat-form-field class="someclass">
<mat-select placeholder="Select payment method" formControlName="paymentMethod">
<mat-option *ngFor="let payment of paymentMethodOptions" [value]="payment.value">
{{payment.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="someclass">
<input matInput placeholder="Some input" formControlName="testInput">
</mat-form-field>
TS
paymentMethodOptions: payment[] = [
{ value: "opt-1", viewValue: "somevalue" },
{ value: "opt-2", viewValue: "anothervalue" }
];
paymentForm = new FormGroup({
paymentMethod: new FormControl("", Validators.required),
testInput: new FormControl({ value: "", disabled: true }, [
Validators.required
])
});
testInput
如果选择的值等于 ,我想禁用"opt-1"
。我尝试了几个选项,但得到了不同的错误并且无法解决。有什么可行的解决方案吗?提前致谢!
解决方案
您可以收听valueChanges
表单的事件:
this.paymentForm.valueChanges.subscribe((value) => {
if(value.paymentMethod == 'opt-1'){
this.paymentForm.controls['testInput'].disable();
}else{
this.paymentForm.controls['testInput'].enable();
}
});
因此,每次select
更改时,valueChanges
都会调用事件,条件启动,它将启用或禁用 formControl。
推荐阅读
- php - 如果我忘记了codeigniter中的加密密钥,如何恢复密码
- c++builder - 你如何设置 TDirect2DCanvas.Pen.StrokeStyle?
- css - Tidio 实时聊天样式
- node.js - 护照中间件不运行
- magento2 - 在 Magento 2.4.2 中 Js 缩小站点采用错误的 js 路径后
- oracle - 即使我安装了 Oracle 也没有打开
- html - 响应式内容满足整个浏览器大小,而不是滚动条
- loops - 在机器人框架中,如何获得 excel 内循环中每个值的总和?
- json - 如何对列中包含 JSON 数据的表进行选择查询
- smartcontracts - 建筑脚蹼合同