【发布时间】:2019-01-26 19:07:44
【问题描述】:
我有几个嵌套的可重用组件,它们各自的状态以它们自己的反应形式。当我使用 formControl-methods disable()/enable() 禁用父组件时,我想启用或禁用所有子 formControls。
背景:在响应式表单中,禁用的 HTML 属性由 formControl 本身控制:
this.formGroup = new FormGroup({
control: new FormControl({ value: '', disabled: true })
});
启用/禁用的切换也是这样完成的:
this.formGroup.get('control')!.enable(); // Or disable()
formGroup 会在 DOM 中为你设置 disabled 属性。
问题: 我遇到的问题是,当我使用 enable()/disable() 时,子禁用 @Input() 的设置器永远不会被调用。我无法将启用/禁用传播到所有子组件。
@Component({
template: `
<ng-container [formGroup]="formGroup">
<child-component formControlName="control"></child-component>
</ng-container>
`})
export class ParentComponent {
...
method(): void {
this.formGroup.get('control')!.enable(); // Or disable()
}
}
在子组件内部,我无法监听父组件的启用:
@Component(...)
export class ChildComponent implements ControlValueAccessor {
@Input()
get disabled(): boolean {
return this._disabled;
}
// This setter never gets called as it would've using a normal @Input().
set disabled(val: boolean) {
this._disabled = val;
}
}
在上面的示例中,如何在 ChildComponent 中监听启用/禁用?
【问题讨论】:
-
你能分享你绑定输入属性的父html吗
-
@Chellappan 我添加了一个模板。我所有的子组件都实现了 ControlValueAccessor。
标签: angular