Angular 5 - Inject a component into another at runtime

I have created a new Angular 5 project using angular-cli.

I have created a new component called parent.component and a panel.component

Now on the app.component.html I have this:

<button (click)="injectPanelIntoParentComponent()">Inject Panel into Parent Component</button>

<app-parent>
   // Everytime the button is clicked I need an instance of the panel.component to be injected here
</app-parent>

Open in new window


How can I do that?
LVL 1
error2013Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael ArciniegaExperts Exchange QACommented:
A great example of how to do this can be found on Angular's main tutorial site: Displaying a List

The basic idea is to have an array in the parent component that contains all of the info for the panels. Your "injectPanelIntoParentComponent()" method would then add one more to this array.

export class AppParent implements OnInit {

  panels = [];

  constructor() { }

  ngOnInit() {
  }

  injectPanelIntoParentComponent() {
	  // add items to the array that holds the info of your panels
	  panels.push({ id: 12, panelTitle: 'Names', foo: 'bar' })
  }
}

Open in new window


Your html for the parent would then use an *ngFor to display all the panels contained in the list.

<ul class="app-parent">
  <li *ngFor="let panel of panels"
    <span class="coolStyle">{{panel.id}}</span> {{panel.panelTitle}}
	<p>{{foo.bar}}</p>
  </li>
</ul>

Open in new window


You can also replace the html inside of the *ngFor with another component described elsewhere:

<ul class="app-parent">
  <li *ngFor="let panel of panels"
    <panel-detail [panel]="panel"></panel-detail>
  </li>
</ul>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
error2013Author Commented:
Perfect thanks!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Angular

From novice to tech pro — start learning today.