繁体   English   中英

在反应形式中动态禁用 formControls

[英]Dynamical disabling of formControls in reactive forms

我有几个嵌套的可重用组件,它们具有各自的反应形式的状态。 当我使用 formControl-methods disable()/enable() 禁用父组件时,我想启用或禁用所有子 formControl。

背景:在响应式表单中,禁用的 HTML 属性由 formControl 本身控制:

this.formGroup = new FormGroup({ 
  control: new FormControl({ value: '', disabled: true }) 
});

启用/禁用的切换​​也是这样完成的:

this.formGroup.get('control')!.enable(); // Or disable()

formGroup 将在 DOM 中为您设置禁用的属性。

问题:我遇到的问题是,当我使用 enable()/disable() 时,孩子的 setter 禁用了 @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 中收听启用/禁用?

这就是我最终让 ChildComponent 知道 ParentComponent 已启用/禁用它的方式:

解决方案1:

const disableChange$ = this.ngControl.statusChanges.pipe(
    map(status => status === 'DISABLED'),
    distinctUntilChanged()
)

其中 ngControl 被注入到 ChildComponent 的构造函数中。

编辑:

解决方案2 (更好的一个):

setDisabledState(isDisabled: boolean): void {
  this.disabled = isDisabled;
  this.stateChanges.next();
}

使用 ChildComponent 中 ControlValueAccessor 接口的 setDisabledState 设置禁用状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM