Angular2: Insert a dynamic component as child of a container in the DOM

TL;DR: replace <div #placeholder></div> with <div><ng-template #placeholder></ng-template></div> to insert inside the div.

Here is a working stackblitz example (Angular 6), and the relevant code:

@Component({
  selector: 'my-app',
  template: `<div><ng-template #container></ng-template></div>`
})
export class AppComponent implements OnInit {

    @ViewChild('container', {read: ViewContainerRef}) viewContainer: ViewContainerRef;

    constructor(private compiler: Compiler) {}

    ngOnInit() {
      this.createComponentFactory(MyDynamicComponent).then(
        (factory: ComponentFactory<MyDynamicComponent>) => this.viewContainer.createComponent(factory),
        (err: any) => console.error(err));
    }

    private createComponentFactory(/*...*/) {/*...*/}

}

It seems <ng-container #placeholder></ng-container> is also working (replace ng-template by ng-container). I like this approach because <ng-container> is clearly addressed to this usecase (a container that don’t add a tag) and can be used in other situations like NgIf without wrapping in a real tag.


PS: @GünterZöchbauer directed me to the right discussion in a comment, and I finally answered my own question.


Edit [2018-05-30]: Updated to stackblitz link to have a working, up-to-date example.

Leave a Comment