注入angular2组件作为指令的子项

时间:2016-12-21 16:11:14

标签: angular

正如标题所示,我想在属于指令的元素中动态插入一个组件。

我有这个:

<div *loadingSpinner="isLoading" class="page-banner banner-welcome">
  <h2>Welcome</h2>
</div>

我正在添加这样的组件:

@Directive({
    selector: "[loadingSpinner]"
})
export class LoadingSpinner implements OnInit {
    @Input()
    set loadingSpinner(showSpinner: boolean) {
        this.toggleSpinner(showSpinner);
    }
    private hostElement: any;
    private spinnerComponent: ComponentRef<LoadingSpinnerComponent>;
    constructor(private templateRef: TemplateRef<any>,
                private viewContainer: ViewContainerRef,
                private resolver: ComponentFactoryResolver) {
        this.hostElement = templateRef.elementRef.nativeElement;
        this.viewContainer.createEmbeddedView(this.templateRef);
    }

    public ngOnInit() {
        let componentFactory = this.resolver.resolveComponentFactory(LoadingSpinnerComponent);
        this.spinnerComponent = this.viewContainer.createComponent(componentFactory);
    }
}

结果是我的LoadingSpinnerComponent在包含该指令的元素之后添加但我需要它在该元素内(在元素之后)

有什么想法吗?

0 个答案:

没有答案