Angular 2.0 final: How to instantiate a component from code

后端 未结 4 1006
[愿得一人]
[愿得一人] 2021-02-05 16:36

I\'m looking for a way to instantiate a component in Angular2 from within the code of another component. Unlike the many people that have asked a similar question I\'m not so mu

4条回答
  •  天命终不由人
    2021-02-05 17:04

    Here's a working demo: https://plnkr.co/edit/pgkgYEwSwft3bLEW95Ta?p=preview

    import {Component, NgModule, ViewChild, ElementRef, Input, Output, EventEmitter, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ReflectiveInjector} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Component({
      selector: 'any-comp',
      template: '
    here i am.. {{name}}
    ' }) export class AnyComponent { @Input() name; @Output() clicked = new EventEmitter(); constructor() { console.log('some1 created me.. ! :)'); } } @Component({ selector: 'my-app', template: `

    Hello {{name}}

    `, }) export class App { @ViewChild('placeHolder', {read: ViewContainerRef}) private _placeHolder: ElementRef; name:string; constructor(private _cmpFctryRslvr: ComponentFactoryResolver) { this.name = 'Angular2' } ngOnInit() { let cmp = this.createComponent(this._placeHolder, AnyComponent); // set inputs.. cmp.instance.name = 'peter'; // set outputs.. cmp.instance.clicked.subscribe(event => console.log(`clicked: ${event}`)); // all inputs/outputs set? add it to the DOM .. this._placeHolder.insert(cmp.hostView); } public createComponent (vCref: ViewContainerRef, type: any): ComponentRef { let factory = this._cmpFctryRslvr.resolveComponentFactory(type); // vCref is needed cause of that injector.. let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector); // create component without adding it directly to the DOM let comp = factory.create(injector); return comp; } } @NgModule({ imports: [ BrowserModule ], declarations: [ App, AnyComponent ], // ! IMPORTANT entryComponents: [ AnyComponent ], // ! IMPORTANT --> would be lost due to Treeshaking.. bootstrap: [ App ] }) export class AppModule {}

提交回复
热议问题