2

我有一个指令来为模板驱动的表单构建动态输入组件。默认值由 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

4

2 回答 2

0

您可以创建 StackBlitz 帖子以进行更好的调试吗?

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

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

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

    this.formgroup.setValue({ key: value },{emitEvent: false})

于 2020-01-17T12:03:24.663 回答
0

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

于 2020-01-17T12:05:02.903 回答