【问题标题】:Angular ControlValueAccessor with default value from internal causes dirty具有内部原因的默认值的角 ControlValueAccessor 脏
【发布时间】:2020-05-04 07:16:08
【问题描述】:

我有一个指令来为模板驱动的表单构建动态输入组件。 默认值由 Input 组件本身设置。

问题是设置默认值会导致表单被标记为脏。

如何在不将表单标记为脏的情况下从指令内部归档设置默认值?

@Directive({
  selector: '[myFormInputFactory]',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyFormFactoryDirective), multi: true }
  ]
})
export class MyFormFactoryDirective implements OnChanges, OnDestroy, ControlValueAccessor {
  @Input() myFormInputFactory: DialogItem;

  private componentRef: any;
  private value: any;
  private valueSubscription: Subscription;
  private disabled = false;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver,
    private _renderer: Renderer,
    private _elementRef: ElementRef
  ) { }

  onChange = (_: any) => { };
  onTouched = () => { };

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }


  ngOnChanges(changes: SimpleChanges) {
    if ('myFormInputFactory' in changes) {
      const config = changes['myFormInputFactory'].currentValue as IConfigItem;

      const factories = Array.from(this.componentFactoryResolver['_factories'].values());
      const comp = factories.find((x: any) => x.selector === config.selector) as ComponentFactory<{}>;
      const componentRef = this.viewContainerRef.createComponent(comp);

      if (this.componentRef) {
        this.componentRef.destroy();
      }
      this.componentRef = componentRef;
      this.valueSubscription = this.componentRef._component.valueChange.subscribe(value => {
        this.value = value;
        this.onChange(this.value);
      });
    }
  }

  ngOnDestroy() {
    if (this.valueSubscription) {
      this.valueSubscription.unsubscribe();
    }
  }

  writeValue(value: string): void {
    if (this.value !== null) {
      this.onChange(this.value);
    }
     if (value !== undefined && value !== null) {
       this.value = value;
    }
  }
}

更新

我创建了一个StackBlitz

【问题讨论】:

标签: javascript angular forms controlvalueaccessor


【解决方案1】:

对于它的价值,我认为问题在于您在writeValue 中调用this.onChangewriteValue 用于通知控件值已被表单外部更改,因此无需调用onChange 通知表单更改。

【讨论】:

  • 我同意。如果您想构建子表单或更简单的 ControlValueAccessor,您应该查看github.com/cloudnc/ngx-sub-form :)
  • 否则表单将无法识别输入控件中的更改
  • 我在子窗体中修补值时遇到了同样的问题。主窗体由于某种原因被标记为脏......你找到解决方案了吗?
【解决方案2】:

您能否创建 StackBlitz 帖子以进行更好的调试?

我认为问题的一部分可能是访问输入而不是访问 FormControl 本身。直接访问输入本身然后触发 onChange 事件并将输入标记为脏,在我看来,这可能是一个问题。

您如何使用该指令?是否可以执行以下操作?

  1. 在父组件中创建 FormGroup
  2. 使用 myFormInputFactory 指令时,将适当的 FormControl 引用传递给指令并将值分配给控件本身:

    this.formgroup.setValue({ 核心价值 },{emitEvent: false})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多