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

后端 未结 2 1414
夕颜
夕颜 2020-12-02 00:25

It seems fine whenever I dump the chart to the main app.component.html, but as soon as I use it in a child component and have the app routed to it, the chart doesn\'t show u

相关标签:
2条回答
  • 2020-12-02 00:34

    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

    0 讨论(0)
  • 2020-12-02 00:37

    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.

    0 讨论(0)
提交回复
热议问题