Chart.js not showing in Angular2 if it doesn't exist on the main page

Solution 1:

Ok, so here's how I solved the issue I was having. I created a new canvas component with just the canvas element and imported my chart directive to the new component. After that, I used the DynamicComponentLoader class to dynamically load my component whenever I create an instance of my home component.

New home.component.ts:

import {Component, DynamicComponentLoader, Injector} from 'angular2/core';
import {TopicsComponent} from './topics.component';
import {CanvasComponent} from './canvas.component';

@Component({
    selector: 'home',
    templateUrl: 'app/home.component.html',
    directives: [TopicsComponent, CanvasComponent]
})

export class HomeComponent { 
    constructor(dcl: DynamicComponentLoader, injector: Injector) {
        dcl.loadAsRoot(CanvasComponent, '#chartInsert', injector);
    }
}

New home.component.html

<div class="container details-container">
  <topics></topics>
</div>

<div class="graph-container">
    <div class="row no-pad" style="position: relative;">
        <div style="margin-left:14px; z-index: 100; height: 250px;" id="chartInsert">   
        </div>  
        <div class="vaxis-bar"></div>
    </div><!--/row-->
    <div class="row">
        <div class="col-sm-12 text-center bottom-row">
            HOURS(9)
        </div>
    </div>
</div>

New canvas.component.ts

import {Component} from 'angular2/core';
import {ChartDirective} from './chart.directive';

@Component({
    selector: 'canvas-component',
    template: '<canvas id="myChart" chart height="250" width="350"></canvas>',
    directives: [ChartDirective]
})

export class CanvasComponent { }

I hope this can help someone out.

Solution 2:

There was a breaking change in Angular 2.0.0-beta.3 regarding ElementRef https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta3-2016-02-03. Instead of using ElementRef inside the constructor you should look at ngOnInit as a LifeCycle hook https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html