Lazloman
Lazloman

Reputation: 1347

Dynamically insert angular component as a child of another component

I've seen a few examples of how to do this here and around the 'net, but when I try it, my child component is inserted into the DOM as a peer of the target component. Here is markup I'm working with:

<div #target></div>
<button (click)="AddTile()">Add Tile</button>

Here is the parent component code:

import { Component, ComponentFactoryResolver, ViewContainerRef, ViewChild }     from '@angular/core';
import { TileComponent } from './tile/tile.component';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

 export class AppComponent{
  title = 'app works!';

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

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private viewContainerRef: ViewContainerRef) {}

  AddTile() {
    const factory =   this.componentFactoryResolver.resolveComponentFactory(TileComponent);
    const res = this.target.createComponent(factory);
  }
}

The output of this code is:

<div #target></div>
<tile-component></tile-component>
<tile-component></tile-component>

The expected output is:

<div #target>
  <tile-component></tile-component>
  <tile-component></tile-component>
</div>

Upvotes: 0

Views: 1681

Answers (1)

Frank Modica
Frank Modica

Reputation: 10516

You may want to use ng-container as your target, which leaves no element in the DOM. So you'll be left with just the component inside your div:

<div>
    <ng-container #target></ng-container>
</div>

Upvotes: 3

Related Questions