2016-11-12 66 views
7

我有一个部件角2插入到@Component另一组件

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'test-component', 
    template: '<b>Content</b>', 
}) 
export class TestPage { 
    constructor() {} 
} 

的DOM我有另一种组分:

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'main-component', 
    templateUrl: 'main.html', 
}) 
export class MainPage { 

    constructor() {} 

    putInMyHtml() { 

    } 
} 

main.html中:

<p>stuff</p> 
<div> <!-- INSERT HERE --> </div> 

我如何动态地将我的TestPage组件插入<!--INSERT HERE-->编程的区域,如wh我运行putInMyHtml

我尝试编辑DOM并插入<test-component></test-component>,但它不显示TestPage模板中的内容文本。

+0

[在角2无法初始化动态追加(HTML)组件(可能的重复http://stackoverflow.com/questions/36566698/cant- initialize-dynamic-html-component-in-angular-2) – echonax

+0

这是正确的解决方案。您是否在浏览器控制台或编译器中收到错误消息? – Martin

+0

@Martin没有错误,它仍然在DOM中的没有角度渲染模板。 – Akshat

回答

11

下面是一个Plunker ExampleComponentFactoryResolver

首先,你必须注册你的动态组件TestPage正确

app.module.ts

@NgModule({ 
    declarations: [MainPage, TestPage], 
    entryComponents: [TestPage] 
}) 

替代选项

声明动态module.ts

import { NgModule, ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core'; 

@NgModule({}) 
export class DynamicModule { 
    static withComponents(components: any[]) { 
    return { 
     ngModule: DynamicModule, 
     providers: [ 
     { 
      provide: ANALYZE_FOR_ENTRY_COMPONENTS, 
      useValue: components, 
      multi: true 
     } 
     ] 
    } 
    } 
} 

app.module.ts

导入
@NgModule({ 
    imports:  [ BrowserModule, DynamicModule.withComponents([TestPage]) ], 
    declarations: [ MainComponent, TestPage ] 
}) 

然后你MainPage成分可能如下:

import { ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; 
@Component({ 
    selector: 'main-component', 
    template: ` 
    <button (click)="putInMyHtml()">Insert component</button> 
    <p>stuff</p> 
    <div> 
     <template #target></template> 
    </div> 
    ` 
}) 
export class MainPage { 
    @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef; 
    constructor(private cfr: ComponentFactoryResolver) {} 

    putInMyHtml() { 
    this.target.clear(); 
    let compFactory = this.cfr.resolveComponentFactory(TestPage); 

    this.target.createComponent(compFactory); 
    } 
} 
+1

奇妙的是,我尝试了很多东西,这是一个令人头疼的问题,Angular不停地变化 – Akshat

1

如果两个部件是相同的模块中,确保他们都宣称第一:

MyModule的

@NgModule({ 
    declarations: [TestPage, MainComponent] 
}) 

如果它们在不同的模块,请确保您已经导出TestPage和将其导入您加载的模块中MainComponent

TestPageModule

@NgModule({ 
    declarations: [TestPage], 
    exports: [TestPage] 
}) 

MainComponent

@NgModule({ 
    declarations: [MainComponent], 
    imports: [TestPage] 
})