1

目前FormGroupDirective.directives仅显示NgControl指令扩展,按照如何将 a 附加到动态创建的组件的SOF 答案实现。FormControlName

export class DynamicPanelDirective extends NgControl implements OnInit  {

  _control: FormControl;

  constructor(
    @Optional() @Host() @SkipSelf() private parent: ControlContainer,
    private resolver: ComponentFactoryResolver,
    private container: ViewContainerRef) {
    super();
  }

  ngOnInit() {
    let component = this.resolver.resolveComponentFactory<GeneralPanelComponent>(GeneralPanelComponent);
    this.name = 'general';
    this.component = this.container.createComponent(component);
    this.valueAccessor = this.component.instance;
    this._control = this.formDirective.addControl(this);
  }
  ...
}

记录时,我得到一个包含所有sthis.parent.formDirective.directives的数组DynamicPanelDirectiveFormGroupDirective

directives: Array(2)
0: DynamicPanelDirective {_parent: null, name: "input", valueAccessor: InputComponent, _rawValidators: Array(0), _rawAsyncValidators: Array(0), …}
1: DynamicPanelDirective {_parent: null, name: "select", valueAccessor: SelectComponent, _rawValidators: Array(0), _rawAsyncValidators: Array(0), …}

这是伟大的。

下一步是扩展NgModelGroup以将其附加formGroupName到动态创建的组,然后将控件附加到它们的托管组

我遵循了这个模式,也得到了这个 github 问题贡献的帮助,并扩展NgModelGroup到了另一个指令 -DynamicGroupDirective

export class DynamicGroupDirective extends NgModelGroup implements OnInit, OnDestroy {
  @Input() config: GroupControlConfig;
  component: ComponentRef<any>;

  constructor(
    @Host() @SkipSelf() private parent: ControlContainer,
    @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
    @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[],
    private resolver: ComponentFactoryResolver,
    private container: ViewContainerRef
  ) {
    super(parent, validators, asyncValidators);
  }

  ngOnInit(): void {
    this.name = this.config.name;
    const factory = this.resolver.resolveComponentFactory<any>(component);
    component = this.container.createComponent(factory);
  }

  get path(): string[] {
    return [...this.config.breadcrumbs !, this.name];
  }

现在每个控件都分配给其适当的组主机

DynamicGroupDirective问题是,我在this.parent.formDirective.directives数组中看不到任何东西,只有DynamicPanelDirectives。

我注意到由于这个附加指令被附加:

// dynamic-panel.directive.ts ~ ngOnInit()
this._control = this.formDirective.addControl(this);

而且我知道我必须使用中的匹配功能DynamicGroupDirective,即

this.parent.formDirective.addFormGroup(this);

但是我不明白我需要分配什么,因为它本身并没有添加到指令数组中,并且我不能分配给this.control它被标记readonly

用例是DynamicGroupDirective使用config.breadcrumbs帮助将其附加到组的正确方法,但我还需要将动态组件本身呈现在其适当的组中ViewContainerRef

所以也许有人有更好的建议。谢谢你读到这里的任何人

4

0 回答 0