当为Angular应用程序中的组件建立模板时,你很可能希望能够在不影响其他组件的情况下,用CSS样式为该特定的组件设置样式。一个特定的模板往往需要一个独特的样式。例如,如果你建立了一个特殊的页脚组件,你可能想用一个不同于其他应用程序的样式来设计超链接。在有嵌套组件的情况下,有几种方法可以将样式应用于嵌套组件而不泄漏到其他组件。在本教程中,我们将看到如何将特定的样式只应用于某些组件。
HTML模板文件的内联CSS
你的第一个选择是简单地在给定模板的HTML中内联CSS规则。这种方法通常适用于你想应用的快速和肮脏的样式,但问题是随着时间的推移,它变得非常混乱,而且更难维护。下面是一个将内联样式直接添加到Angular模板文件的例子。
game-list.component.html
<table class='table' *ngIf='games && games.length'>
<thead>
<tr>
<th>
<button class='btn btn-primary'
(click)='toggleImage()'>
{{showImage ? 'Hide ' : 'Show'}} Image
</button>
</th>
<th style="color:firebrick">Game</th>
<th>Part#</th>
<th>Release Date</th>
<th>Cost</th>
<th>5 Thumb Rating</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let game of games'>
<td>
<img *ngIf='showImage'
[src]='game.imageUrl'
[title]='game.gameName'
[style.width.px]='imageWidth'
[style.margin.px]='imageMargin'>
</td>
<td>{{ game.gameName }}</td>
<td>{{ game.gameCode | lowercase }}</td>
<td>{{ game.releaseDate }}</td>
<td>{{ game.price | currency:'USD':'symbol':'1.2-2' }}</td>
<td>{{ game.thumbRating }}</td>
</tr>
</tbody>
</table>

封装Angular的样式
组件装饰器有内置的属性,允许开发者直接将样式封装为组件的一部分。这些是styles 和**styleUrls** 属性。
使用 styles
与 styles属性,你可以将一个或多个样式直接应用在 styles属性中。下面是一个例子。
game-list.component.ts
import {Component} from '@angular/core';
import {IGame} from './game';
@Component({
selector: 'game-list',
templateUrl: './game-list.component.html',
styles: ['th:nth-child(3) {color:deepskyblue}']
})
export class GameListComponent {
pageTitle = 'Dynamic! Game List';
imageWidth = 45;
imageMargin = 1;
showImage = true;
listItem = 'Mario';
games: IGame[] = [...];
toggleImage(): void {
this.showImage = !this.showImage;
}
}

使用 styleUrls
的两个 style和 styleUrls属性都是数组。这意味着,在 styles的情况下,你可以为每个数组位置应用多个样式定义。在的情况下 styleUrls的情况下,你可以在每个数组位置指定一个链接的样式表。这意味着你可以把不同的css规则分割成不同的css样式表,如果你愿意的话。为了使用 styleUrls属性,首先我们可以为这个组件创建一个外部样式表来链接。

将样式封装在组件中的目的是为了让任何选择器或类的使用只针对这个特定的组件。这样,当样式被封装时,你不会在页面的其他地方得到意外的结果。这是一个很大的好处。然而,在我们可以在这个新的样式表中应用样式之前,我们必须把它连接起来。下面是如何做到这一点的。
game-list.component.ts
import {Component} from '@angular/core';
import {IGame} from './game';
@Component({
selector: 'game-list',
templateUrl: './game-list.component.html',
styleUrls: ['./game-list.component.css']
})
export class GameListComponent {
pageTitle = 'Dynamic! Game List';
imageWidth = 45;
imageMargin = 1;
showImage = true;
listItem = 'Mario';
games: IGame[] = [...];
toggleImage(): void {
this.showImage = !this.showImage;
}
}
一旦外部样式表被链接在 styleUrls属性中链接,我们就可以在game-list.component.css文件中添加一些样式规则,像这样。
th:nth-child(4) {
color: lightslategrey;
}

注意:在处理组件装饰器中应用css样式时,你需要选择一种或另一种方法。换句话说,要么在style属性中放一个样式规则数组,要么在styleUrls属性中链接一个外部样式表。它们不能一起工作。因此,在大多数情况下,只使用styleUrls属性和一个链接的样式表可能更容易和更方便。
总结
在Angular中封装样式是可以通过在组件本身定义样式来实现的。这允许定义的样式只针对给定的组件,而不会泄漏到应用程序的其他部分。
- styles属性:用于指定一个声明的样式数组。适合于非常简单的样式定义。
- styleUrls属性:用于指定一个链接样式表路径的数组。更适合于一个更有组织的样式声明的布局。
使用这两种方法中的一种,会导致给定的样式被封装在组件中。