【问题标题】:Need to include separate components of charts (chart.js) with settings in other (dashboard) component需要在其他(仪表板)组件中包含单独的图表组件(chart.js)和设置
【发布时间】:2019-06-18 05:52:31
【问题描述】:

我有四个独立的组件,每个 (chart.js) 中有四种不同类型的图表,其中还包括图表的设置。我想根据不同组件的后端响应包含特定图表。

我使用 @ViewChild 访问特定组件的方法/变量,并在 dashboard.component.html 中包含组件的 HTML。我正在使用 *ngFor 因为我正在从后端获得响应,然后使用 *ngIf 来调用/包括特定的

我也尝试过 ComponentFactory 创建特定组件,但由于无法访问包含组件的方法而放弃了这种方法。

<--HTML CODE-->
<div class="col-xl-6 mb-4" *ngFor="let graphs of 
 dashboardRes?.data?.dashboard_graphs">
<app-sales-pipeline *ngIf="graphs?.chart_detail?.type == 
'horizontal_bar_chart'"></app-sales-pipeline>
<app-line-chart *ngIf="graphs?.chart_detail?.type == 'line_chart'"></app- 
line-chart>
<app-gauge-chart *ngIf="graphs?.chart_detail?.type == 'guage_chart'"> 
</app-gauge-chart>
</div>

<--TS CODE-->
@ViewChild(LineChartComponent) lineChart: LineChartComponent;
@ViewChild(BarChartComponent) barChart: BarChartComponent;
@ViewChild(GaugeChartComponent) gaugeChart: GaugeChartComponent;

// Not using this approach as i was unable to access included component's methods.
createBarChart(): void {
const factory: ComponentFactory<any> = 
this.resolver.resolveComponentFactory(BarChartComponent);
this.componentRef = this.container.createComponent(factory);
}

我想在应用程序中任何需要的地方动态地包含图表组件。我还想调用他们的特定方法来通过 API 检索图表数据。图表类型、图表设置和图表数量将出现在 Dashboard API 中,其中图表数据应带有其特定组件(因为我也将在报告页面中包含这些图表 - 使用不同的数据)。我主要关心的是使用 API 更改特定图表的设置并保存它们(设置来自仪表板 API)

【问题讨论】:

    标签: angular angular7


    【解决方案1】:

    我建议您不要重用组件方法。您可以像使用 *ngFor*ngIf 一样启动组件,但您可以将来自 API 的设置动态设置为输入并在组件时设置开始。如果您想重用已经从仪表板获取的数据,您可以将图形模型传递给子组件,否则您可以使用角度生命周期在 ngOnInit() 上调用每个组件上的 api。 p>

    如果您希望重用已获取的图表,您的图表组件将具有如下输入:

    export class BarChartComponent implements OnInit {
      @Input() chartModel: ChartModel;
    
      ngOnInit() {
         this.methodIWantToCallToUpdateSettings();
      }
    
      methodIWantToCallToUpdateSettings(): void {
         //do your thing
      }
    }
    

    您的dashboard.component.html 将如下所示:

    <app-bar-chart *ngIf="graphs?.chart_detail?.type == 'bar_chart'" [chartModel]="graphs"> 
    

    现在,如果您想由每个组件动态调用它,只需在 ngOnInit() 图表组件上添加对后端的调用,并通过输入传递您想要传递的参数.

    类似这样的:

    export class BarChartComponent implements OnInit {
      @Input() parameter: string;
    
      ngOnInit() {
         this.callToBackEnd(this.parameter);
      }
    
      callToBackEnd(parameter: string): void {
         //do your thing on backend
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 2011-12-06
      • 2013-05-02
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多