目前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
的数组DynamicPanelDirective
FormGroupDirective
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
数组中看不到任何东西,只有DynamicPanelDirective
s。
我注意到由于这个附加指令被附加:
// dynamic-panel.directive.ts ~ ngOnInit()
this._control = this.formDirective.addControl(this);
而且我知道我必须使用中的匹配功能DynamicGroupDirective
,即
this.parent.formDirective.addFormGroup(this);
但是我不明白我需要分配什么,因为它本身并没有添加到指令数组中,并且我不能分配给this.control
它被标记readonly
用例是DynamicGroupDirective
使用config.breadcrumbs
帮助将其附加到组的正确方法,但我还需要将动态组件本身呈现在其适当的组中ViewContainerRef
所以也许有人有更好的建议。谢谢你读到这里的任何人