Angular 2将@Component插入另一个组件的DOM中

Aks*_*hat 10 javascript angular

我有一个组件

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

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

我有另一个组成部分:

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

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

  constructor() {}

  putInMyHtml() {

  }
}
Run Code Online (Sandbox Code Playgroud)

main.html中:

<p>stuff</p>
<div> <!-- INSERT HERE --> </div>
Run Code Online (Sandbox Code Playgroud)

如何以编程方式将TestPage组件动态插入到区域中<!--INSERT HERE-->,就像我运行时一样putInMyHtml.

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

yur*_*zui 14

这是一个带有ComponentFactoryResolverPlunker示例

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

app.module.ts

@NgModule({
  declarations: [MainPage, TestPage],
  entryComponents: [TestPage]
})
Run Code Online (Sandbox Code Playgroud)

替代选择

声明dynamic-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
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并在app.module.ts中导入它

@NgModule({
  imports:      [ BrowserModule, DynamicModule.withComponents([TestPage]) ],
  declarations: [ MainComponent, TestPage ]
})
Run Code Online (Sandbox Code Playgroud)

然后您的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);
  }
}
Run Code Online (Sandbox Code Playgroud)