How to apply themes in angular2?

前端 未结 2 897
予麋鹿
予麋鹿 2021-01-21 14:01

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

相关标签:
2条回答
  • 2021-01-21 14:45

    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');
        }
    }
    
    0 讨论(0)
  • 2021-01-21 14:51

    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;
    }
    
    0 讨论(0)
提交回复
热议问题