Angular 追加到FormGroupDirective的指令[]
当前Angular 追加到FormGroupDirective的指令[],angular,angular-reactive-forms,angular2-directives,angular-dynamic-components,Angular,Angular Reactive Forms,Angular2 Directives,Angular Dynamic Components,当前FormGroupDirective.directives仅显示NgControl指令扩展, 以下是如何将FormControlName附加到动态创建的组件的答案 export class DynamicPanelDirective extends NgControl implements OnInit { _control: FormControl; constructor( @Optional() @Host() @SkipSelf() private parent
FormGroupDirective.directives
仅显示NgControl
指令扩展,
以下是如何将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);
}
...
}
这很好
下一步是扩展NgModelGroup
,将formGroupName
附加到动态创建的组,然后将控件附加到它们的宿主组
我遵循了这个模式,并在NgModelGroup
的帮助下将其扩展到另一个指令-DynamicGroupDirective
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), …}
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.addFormGroup(this);
但是我不明白我需要在中分配什么,因为它本身并没有添加到指令数组中,而且我不能分配给this.control
,因为它标记为只读
用例是使用有助于将动态组件附加到组的config.breadcrumbs
访问正确的DynamicGroupDirective
,但我还需要在其正确的组中呈现动态组件本身ViewContainerRef
所以也许有人有更好的建议。。
感谢所有读过这篇文章的人
this.parent.formDirective.addFormGroup(this);