7

In angular 2, is it possible to manually instantiate a component A, then pass it around and render in the template of component B?

luke
  • 73
  • 1
  • 3
  • Welcome to SO please check this [URL](http://stackoverflow.com/help)it will be helping you to raise your question content quality – Willie Cheng May 06 '16 at 02:57

1 Answers1

0

Yes, that's supported. You need a ViewComponentRef that can for example be acquired by injecting it to the constructor or using a @ViewChild('targetname') query and a ComponentResolver that also can be injected.

This code example from https://stackoverflow.com/a/36325468/217408 allows for example to add components dynamically with *ngFor

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567