1

I'm learning Angular 2. I've created a component with the following template.

<h1>My component</h1>
<placeholder?></placeholder?>

Depending on the state in my component I want to display different child components instead of the placeholder tag. Is that possible? How?

For example: Let's say I have injected a service into my component. If this service returns 1 I want to show ComponentOne and for all other values from the service I want to display the OtherComponent.

QoP
  • 27,388
  • 16
  • 74
  • 74
Erik Z
  • 4,660
  • 6
  • 47
  • 74

3 Answers3

0

You can use DynamicComponentLoader for this.

See Angular 2 dynamic tabs with user-click chosen components for an example how to use it. I guess the wrapper used in the linked answer would work for you as well.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Use *ngIf for each component you want to display or not :

<component1 *ngIf="service.value1"></component1>

<component2 *ngIf="service.value2"></component2>
Tiberiu Popescu
  • 4,486
  • 2
  • 26
  • 38
0

I would suggest using *ngIf for applying your conditions along with dynamic component loader. You can follow this plnkr for more reference too.

Dynamic Component Loader Example

All you need to do is to apply *ngIf directive on div where you want to load the component.

For eg.

//our root app component
import {Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2'

@Component({
  selector: 'dc',
  template: '<b>Some template</b>'
})   

class DynamicComponent {}

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="your condition">
        <div #container></div>
    </div>
  `
})   

export class App {
  dynamicComponentLoader: DynamicComponentLoader;
  constructor(dynamicComponentLoader: DynamicComponentLoader, elementRef: ElementRef) {
    this.dynamicComponentLoader = dynamicComponentLoader;
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');

  }

}
Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131