如果您使用 angular-cli 并希望全局更改组件的样式,只需将 CSS 属性添加到 style.css 文件中,您将在 src 中找到项目文件夹:
{
"project": {
...
},
"apps": [
{
...
"styles": [
"styles.css"
]
...
请注意,在旧版本的 angular-cli 中,此文件的调用方式可能不同。看看你的 angular-cli.json 文件:在 apps 属性中应该有一个 styles 属性定义了一组样式表将在全球范围内应用。
另一种更改样式的方法,独立于 angular-cli,取决于您使用的视图封装模式。默认情况下,Angular 2 使用“Emulated”,它将 CSS 范围限定为单个组件。如果您只想在一个组件中覆盖文本字段的样式,请通过设置相应的样式属性来实现:
@Component({
selector: 'my-component',
template: require('./template_my-component.html'),
styles: ['mdl-textield { color: red; ...}']
})
如果你想全局覆盖它的样式,你可以将 View Encapsulation 设置为 None,这样可以防止 CSS 被限定在全局范围内。确保导入 ViewEncapsulation。
import {ViewEncapsulation} from '@angular/core';
@Component({
selector: 'my-component',
template: require('./template_my-component.html'),
styles: ['mdl-textield { color: red; ...}'],
encapsulation: ViewEncapsulation.None
})
但要小心,因为如果您开始为不同文件中的相同元素设置不同的属性,这可能会导致一团糟。