Angular 如何通过自定义指令动态添加组件

Angular 如何通过自定义指令动态添加组件,angular,Angular,我想写一个自定义指令,它将根据div中的一些逻辑动态添加组件,我在div中使用了我的自定义指令 我尝试使用componentFactoryResolver和viewContainerRef.createComponent动态添加组件 <div myDirective> <!-- dynamically add component through directive --> <span>Hello</span> </div>

我想写一个自定义指令,它将根据div中的一些逻辑动态添加组件,我在div中使用了我的自定义指令

我尝试使用componentFactoryResolver和viewContainerRef.createComponent动态添加组件

<div myDirective> 
   <!-- dynamically add component through directive -->
   <span>Hello</span> 
</div>

// my custom directive

myDirective {
    constructor( private element: ElementRef,
        private renderer: Renderer,
        private viewContainerRef: ViewContainerRef,
        private componentFactoryResolver: ComponentFactoryResolver
    ) { }

    ngOnInit() {
        let componentFactory = this.componentFactoryResolver
                    .resolveComponentFactory(myComponent);
        let componentRef = this.viewContainerRef
                    .createComponent(componentFactory, 0);
    }

}

你好
//我的自定义指令
我的指令{
构造函数(私有元素:ElementRef,
私有渲染器:渲染器,
私有viewContainerRef:viewContainerRef,
专用componentFactoryResolver:componentFactoryResolver
) { }
恩戈尼尼特(){
让componentFactory=this.componentFactoryResolver
.ResolveComponent工厂(myComponent);
让componentRef=this.viewContainerRef
.createComponent(componentFactory,0);
}
}
实际结果:在div之后创建组件,
预期:应将组件添加到div中

您可以为此使用ng模板:

<div> 
<ng-template myDirective>
   <!-- dynamically add component through directive -->
</ng-template>
   <span>Hello</span> 
</div>

你好
检查我刚刚创建的这个示例

希望这能奏效

注意:如果您想以惰性和动态方式加载组件,请签入演示文稿

更新:我在指令中加入了一些逻辑。另外,我不明白您为什么不想添加ng模板。

将动态创建的组件放置在宿主元素旁边

@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
  constructor(private element: ElementRef,
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver
      .resolveComponentFactory(DynamicComponent);

    const componentRef = this.viewContainerRef.createComponent(componentFactory);

    const host = this.element.nativeElement;
    host.insertBefore(componentRef.location.nativeElement, host.firstChild)
  }
} 
但您可以通过将创建的元素移动到宿主元素中来更改此行为

@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
  constructor(private element: ElementRef,
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver
      .resolveComponentFactory(DynamicComponent);

    const componentRef = this.viewContainerRef.createComponent(componentFactory);

    const host = this.element.nativeElement;
    host.insertBefore(componentRef.location.nativeElement, host.firstChild)
  }
} 

谢谢@mikaovA的回答,但我不想不必要地到处添加ng模板,因为我将在很多地方使用此自定义指令。另外,指令必须具有动态添加组件的逻辑。我不知道您为什么避免使用
ng模板