1

What is the proper way to display components dynamically in a view?

As an example, I have a component which has a navigation and a view. Clicking a button in the navigation different sub-components should appear/disappear in the view. Each of the sub-components are of a different type.

import { Component, Input } from '@angular/core';
import { Controls } from './controls.service';

@Component({
  selector: 'Controlpanel',
  templateUrl: 'app/templates/controlPanel.component.html',
  directives: Controls.directives()
})
export class ControlPanelComponent {
  controls = Controls.objects;
  activeControl:string = Controls.objects[0].name;
}

--

<nav class="container-fluid">
    <div class="row">
            <a *ngFor="let control of controls" (click)="toggleControl(control.name, $event)" role="button" href="#" class=" text-uppercase"> 
                {{control.name}}
            </a>
    </div>
</nav>
<div>
    <this is where i want the sub-component to appear/>
</div>
cocoseis
  • 1,443
  • 1
  • 13
  • 35
  • Sounds like a dup of http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468. Is this actually about directives or components? You can't dynamically add/remove directives. – Günter Zöchbauer Sep 05 '16 at 11:51

1 Answers1

2

You can do something like adding each control you want to load on your form and add an *ngIf to each control but I wouldn't go that way.

Add a where you want to load the directive. And create a childRoute that shows the component(directive) you want to show:

<nav class="container-fluid">
    <div class="row">
            <a *ngFor="let control of controls" (click)="toggleControl(control.name, $event)" role="button" href="#" class=" text-uppercase"> 
                {{control.name}}
            </a>
    </div>
</nav>
<div>
      <!-- this is where you show your sub-component t by routing -->
     <router-outlet></router-outlet>

    </div>
Marcel Hoekstra
  • 1,334
  • 12
  • 19