【问题标题】:Angular 2.1 append component dynamicly inside directiveAngular 2.1 在指令内动态附加组件
【发布时间】:2016-10-19 17:54:22
【问题描述】:

我是 Angular 2.1 的初学者。我想为自动翻译装饰一些元素,我将使用指令,它必须看起来像:

<span customDirectiveTranslation="translateble">{{translateble}}</span>

或者只是

<span customDirectiveTranslation>{{translateble}}</span>

我可以在指令类 (createElement) 中使用渲染器,但通过这种方式,我只能附加像 span 这样的简单元素。

如何通过自定义指令在另一个组件中渲染组件? 谢谢

【问题讨论】:

    标签: angular typescript


    【解决方案1】:
    constructor(
        private target:ViewContainerRef, 
        private componentFactoryResolver: ComponentFactoryResolver, 
        private compiler: Compiler) {}
    
    ngAfterViewInit() {
      this.createComponent();
    }
    
    createComponent() {
        let factory = this.componentFactoryResolver.resolveComponentFactory(MyDynamicComponent);
        this.cmpRef = this.target.createComponent(factory)
    }
    

    另见Angular 2 dynamic tabs with user-click chosen components

    【讨论】:

    • 但是在我的指令的一些代码的链接中,我有一个异常: 异常:./TagComponent 类 TagComponent 中的错误 - 内联模板:0:0 原因:没有为 TestComponentComponent 找到组件工厂
    • 您需要在@NgModule() 中将TestComponentComponent 添加到entryComponents 以便创建工厂。
    • O_O 我不敢相信
    • 通过这种方式,新组件将在指令标记的组件之后(或之前)创建,我可以将新组件放入其中吗?
    • 不,仅作为兄弟姐妹。你需要一个元素内部的ViewContainerRef,然后你可以在里面添加它。
    猜你喜欢
    • 2018-12-15
    • 2016-06-10
    • 2018-08-28
    • 2019-12-06
    • 2019-04-26
    • 1970-01-01
    • 2017-12-18
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多