在反应形式中动态禁用formControl

时间:2018-08-20 15:50:32

标签: angular

我有几个嵌套的可重用组件,它们各自的状态以其自己的反应形式。当我使用formControl方法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()时,子级禁用的@Input()的setter永远不会被调用。我无法将启用/禁用功能传播到所有子组件。

@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中监听启用/禁用?

1 个答案:

答案 0 :(得分:1)

这就是我最终让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设置禁用状态。