简体   繁体   中英

How to display a ng2-chart with Angular 2 on dropdown menu click?

I want that if the user presses a button , a chart to show op on the page. I want to write this html into innerHTML:

<div style="display: block">
<canvas baseChart
      [datasets]="barChartData"
      [labels]="barChartLabels"
      [options]="barChartOptions"
      [chartType]="barChartType"
      [legend]="barChartLegend"></canvas>
</div>

I tried to copy it like this but the chart doesnt show op. I think it doesnt read the properties well.

document.getElementById("info").innerHTML = " <div style=\"display: block\">\n" +
  "  <canvas baseChart\n" +
  "          [datasets]=\"barChartData\"\n" +
  "          [labels]=\"barChartLabels\"\n" +
  "          [options]=\"barChartOptions\"\n" +
  "          [chartType]=\"barChartType\"\n" +
  "          [legend]=\"barChartLegend\"></canvas>\n" +
  "</div>  some text <br>\n" +
  "  some more text: <strong> "+ this.item + "</strong><br>\n" +
  "\n" +
  "  some more text:  <br>\n" +
  "  Monday: <strong> " + this.percentMonday + "%</strong>  <br>\n" 

However when I put it in html file it shows up properly. How can I achieve this? Thanks in advance

   div class="dropdown" dropdown [dropdownToggle]="false">
  <button class="btn btn-primary" dropdown-open>Kies een stad voor meer info</button>
  <ul class="dropdown-menu">

    <li value="Amsterdam" (click)="goToAmsterdam()"><a>Amsterdam</a></li>



  </ul>

</div>

It is quite easily, if your are not neccessarily have to use innerHTML : Firstly, do not use native JavaScript, if you are using Angular(2). Secondly, just add this lines to your code.

JS inside your corresponding Controller:

//...
export class YOURCOMPONENT implements OnInit {
  showChart: boolean; // store toggle state of the chart

  constructor () { }

  ngOnInit(): void {
    this.showChart = false; // hide chart at the beginning
  }
}

HTML:

<div *ngIf="showChart">
    <canvas baseChart
      [datasets]="barChartData"
      [labels]="barChartLabels"
      [options]="barChartOptions"
      [chartType]="barChartType"
      [legend]="barChartLegend"></canvas>
</div>
<button (click)="showChart=!showChart">Toggle Chart</button>

(click)="showChart=!showChart" means that on clicking the button the value of showChart will swap from true to false and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM