I need to provide two themes(red, blue) for the web application that I am developing in angular2. When I change the theme, all the components should reflect it?
What are
You can use the DOCUMENT token from @angular/platform-browser to gain access to all DOM element and then change the stylesheet source. Below is a simple example.
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({})
export class SomeComponent {
constructor (@Inject(DOCUMENT) private document) { }
Light() {
this.document.getElementById('theme').setAttribute('href', 'light.css');
}
}
I am assuming that there are two buttons: one for red and other for blue. The theme will change based on button click of user.
Assign button click events as demoed in your HTML:
<button (click)="Red()">Red</button>
<button (click)="Blue()">Blue</button>
Suppose you want theme change here in div section,
<div id="div1">
---
</div>
In Angular 2 you have to assign classes dynamically for css.
Red(){
document.getElementById('div1').className= 'redClass'; //notice id of div is div1
}
Blue(){
document.getElementById('div1').className='blueClass';
}
Now finally, In css change styling according to class:
div.redClass {
background-color :red;
}
div.blueClass {
background-color :blue;
}