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

后端 未结 2 1427
夕颜
夕颜 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: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

    HOURS(9)

    New canvas.component.ts

    import {Component} from 'angular2/core';
    import {ChartDirective} from './chart.directive';
    
    @Component({
        selector: 'canvas-component',
        template: '',
        directives: [ChartDirective]
    })
    
    export class CanvasComponent { }
    

    I hope this can help someone out.

提交回复
热议问题