0

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>
2
  • are you planning to use different dynamic components based on user action? Commented Sep 16, 2017 at 23:39
  • No, the same component. It won't be based on user action either, but I'll need to dynamically add a varying number of those components at runtime. I'm using a button here as part of a POC. Commented Sep 17, 2017 at 0:12

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

This does work. I had tried using a div, which does yield the same result, except, of course that the div remains in the DOM, which although not a show stopper, it is still undesirable. Thanks
You're welcome. I am wondering now, since the component is always the same, can't you just add ngFor in your template which loops over a dummy array whose length is the number of components you need?
That is an option as well. I'm investigating the various ways to do this. Looping might actually be easiest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.