Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - Angular 2 insert a @Component into the DOM of another component

I have a component

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

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

And I have another component:

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>

How can I dynamically insert my TestPage component into the area where <!--INSERT HERE--> is programatically, like when I run putInMyHtml.

I tried editing the DOM and inserting <test-component></test-component> but it doesn't display the content text from TestPage's template.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an Plunker Example with the ComponentFactoryResolver

Firstly you have to register your dynamic component TestPage properly

app.module.ts

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

Alternative option

Declare 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
        }
      ]
    }
  }
}

and import it in app.module.ts

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

Then your MainPage component might look as follows:

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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...