在反应式表单中勾选复选框时启用
Enable When Checkbox is Check in Reactive Forms
我需要帮助才能使行仅在选中复选框时启用。默认行应该被禁用,但当复选框仅被选中时,该行将被启用。这是我的代码
的 link
patchValues() {
let rows = this.myForm.get('rows') as FormArray;
this.orders.forEach(material => {
material.materials.forEach(x => {
rows.push(this.fb.group({
checkbox_value: [null],
material_id: new FormControl({value: x.id, disabled: true}, Validators.required),
material_name: x.name,
quantity: [null, Validators.required]
}))
})
})
}
Have a look at the Demo & Src
Explanation:
- 要启用或禁用输入字段,您需要使用以下语法
[attr.disabled]="myForm.get('rows').value[i].checkbox_value ? null: ''"
attr.disabled
,这里的 attr 用于绑定不直接存在于元素上的属性
myForm.get('rows').value[i].checkbox_value
,是对表单控件值的直接访问。
另一种方法是创建指令
@Directive({
selector: '[enabledControl]'
})
export class EnabledControlDirective {
@Input() set enabledControl(condition: boolean) {
if (this.ngControl) {
if (this.ngControl.control) {
if (condition)
this.ngControl.control.enable();
else
this.ngControl.control.disable();
}
}
}
constructor(private ngControl : NgControl ) {
}
}
那你可以用like
<input class="col-md-6" formControlName="quantity"
[enabledControl]="row.get('checkbox_value').value" >
我需要帮助才能使行仅在选中复选框时启用。默认行应该被禁用,但当复选框仅被选中时,该行将被启用。这是我的代码
的 link patchValues() {
let rows = this.myForm.get('rows') as FormArray;
this.orders.forEach(material => {
material.materials.forEach(x => {
rows.push(this.fb.group({
checkbox_value: [null],
material_id: new FormControl({value: x.id, disabled: true}, Validators.required),
material_name: x.name,
quantity: [null, Validators.required]
}))
})
})
}
Have a look at the Demo & Src
Explanation:
- 要启用或禁用输入字段,您需要使用以下语法
[attr.disabled]="myForm.get('rows').value[i].checkbox_value ? null: ''"
attr.disabled
,这里的 attr 用于绑定不直接存在于元素上的属性myForm.get('rows').value[i].checkbox_value
,是对表单控件值的直接访问。
另一种方法是创建指令
@Directive({
selector: '[enabledControl]'
})
export class EnabledControlDirective {
@Input() set enabledControl(condition: boolean) {
if (this.ngControl) {
if (this.ngControl.control) {
if (condition)
this.ngControl.control.enable();
else
this.ngControl.control.disable();
}
}
}
constructor(private ngControl : NgControl ) {
}
}
那你可以用like
<input class="col-md-6" formControlName="quantity"
[enabledControl]="row.get('checkbox_value').value" >