Home > database >  How to update the theme of highchart
How to update the theme of highchart

Time:05-28

I have a following code that allows me to switch the theme of highchart between light and dark but it does not get updated. The theme only switches after refreshing the page. Is there a way to do this without refreshing it?

ngAfterViewInit(){
    Highcharts.setOptions(getOptions(this.isLightTheme ? ThemeName.PROFESSIONAL_LIGHT: ThemeName.PROFESSIONAL_DARK));
}

CodePudding user response:

You need to recreate the chart to apply Highcharts.setOptions theme change. The simplest solution to do that in Angular seems to be conditional rendering of two highcharts-chart components. Example:

HTML:

<div>
  <highcharts-chart 
    [Highcharts]="Highcharts"
    [options]="chartOptions"
    *ngIf="isLightTheme;"
    >
  </highcharts-chart>

  <highcharts-chart 
    [Highcharts]="Highcharts"
    [options]="chartOptions"
    *ngIf="!isLightTheme;"
    >
  </highcharts-chart>

  <button (click)="changeTheme()">Change theme</button>
</div>

Component:

Highcharts.setOptions(theme2);
 
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  Highcharts: typeof Highcharts = Highcharts;
  isLightTheme = true;

  chartOptions: Highcharts.Options = {...};

  changeTheme() {
    Highcharts.setOptions(this.isLightTheme ? theme1 : theme2);
    this.isLightTheme = !this.isLightTheme;
  }
}

Live demo: https://stackblitz.com/edit/highcharts-angular-update-optimal-way-qge3vg?file=src/app/app.component.ts

Docs: https://github.com/highcharts/highcharts-angular#readme

  • Related