【发布时间】:2016-09-19 08:15:11
【问题描述】:
我需要为我在 angular2 中开发的 Web 应用程序提供两个主题(红色、蓝色)。当我更改主题时,所有组件都应该反映它?
在 angular2 中应用主题的最佳做法是什么?
【问题讨论】:
标签: angular
我需要为我在 angular2 中开发的 Web 应用程序提供两个主题(红色、蓝色)。当我更改主题时,所有组件都应该反映它?
在 angular2 中应用主题的最佳做法是什么?
【问题讨论】:
标签: angular
您可以使用@angular/platform-browser 中的DOCUMENT token 来访问所有DOM 元素,然后更改样式表源。下面是一个简单的例子。
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');
}
}
【讨论】:
我假设有两个按钮:一个用于红色,另一个用于蓝色。主题将根据用户的按钮点击而改变。
按照 HTML 中的演示分配按钮单击事件:
<button (click)="Red()">Red</button>
<button (click)="Blue()">Blue</button>
假设你想在 div 部分更改主题,
<div id="div1">
---
</div>
在 Angular 2 中,您必须为 css 动态分配类。
Red(){
document.getElementById('div1').className= 'redClass'; //notice id of div is div1
}
Blue(){
document.getElementById('div1').className='blueClass';
}
现在最后,在 css 中根据类更改样式:
div.redClass {
background-color :red;
}
div.blueClass {
background-color :blue;
}
【讨论】: