我们有几种方式来把样式加入组件:
-
内联在模板的 HTML 中
-
设置
styles
或styleUrls
元数据 -
通过 CSS 文件导入
上述作用域规则对所有这些加载模式都适用。
元数据中的样式
我们可以给@Component
装饰器添加一个styles
数组型属性。 这个数组中的每一个字符串(通常也只有一个)定义一份 CSS。
@Component({
selector: 'hero-app',
template: `
<h1>Tour of Heroes</h1>
<hero-app-main [hero]=hero></hero-app-main>`,
styles: ['h1 { font-weight: normal; }']
})
export class HeroAppComponent {
/* . . . */
}
模板内联样式
我们也可以把它们放到<style>
标签中来直接在 HTML 模板中嵌入样式。
@Component({
selector: 'hero-controls',
template: `
<style>
button {
background-color: white;
border: 1px solid #777;
}
</style>
<h3>Controls</h3>
<button (click)="activate()">Activate</button>
`
})
元数据中的样式表 URL
我们还可以通过给组件的@Component
装饰器中添加一个styleUrls
属性来从外部 CSS 文件中加载样式:
@Component({
selector: 'hero-details',
template: `
<h2>{{hero.name}}</h2>
<hero-team [hero]=hero></hero-team>
<ng-content></ng-content>
`,
styleUrls: ['app/hero-details.component.css']
})
export class HeroDetailsComponent {
/* . . . */
}
URL是相对于应用程序根目录的,它通常是应用的宿主页面index.html
所在的地方。 这个样式文件的 URL 不是相对于组件文件的。这就是为什么范例中的 URL 用app/
开头。 参见附录 2 来了解如何指定相对于组件文件的 URL。
像 Webpack 这类模块打包器的用户可能会使用styles
属性来在构建时从外部文件中加载样式。它们可能这样写:
styles: [require('my.component.css')]
注意,这时候我们是在设置styles
属性,而不是styleUrls
属性! 是模块打包器在加载 CSS 字符串,而不是 Angular。 Angular 看到的只是打包器加载它们之后的 CSS 字符串。 对 Angular 来说,这跟我们手写了styles
数组没有任何区别。 要了解这种 CSS 加载方式的更多信息,请参阅相应模块打包器的文档。
模板中的 link 标签
我们也可以在组件的 HTML 模板中嵌入<link>
标签。
像styleUrls
标签一样,这个 link 标签的href
指向的 URL 也是相对于应用的根目录的,而不是组件文件。
@Component({
selector: 'hero-team',
template: `
<link rel="stylesheet" href="app/hero-team.component.css">
<h3>Team</h3>
<ul>
<li *ngFor="let member of hero.team">
{{member}}
</li>
</ul>`
})
CSS @imports
我们还可以利用标准的 CSS @import
规则来把其它 CSS 文件导入到我们的 CSS 文件中。
在这种情况下,URL 是相对于我们执行导入操作的 CSS 文件的。
app/hero-details.component.css (excerpt)
@import 'hero-details-box.css';
附录 2:使用相对 URL 加载样式
把组件的代码 (ts/js)、HTML 和 CSS 分别放到同一个目录下的三个不同文件,是一个常用的实践:
quest-summary.component.ts
quest-summary.component.html
quest-summary.component.css
我们会通过设置元数据的templateUrl
和styleUrls
属性把模板和 CSS 文件包含进来。 既然这些文件都与组件(代码)文件放在一起,那么通过名字,而不是到应用程序根目录的全路径来指定它,就会是一个漂亮的方式。
通过把组件元数据的moduleId
属性设置为module.id
,我们可以更改 Angular 计算完整 URL 的方式
app/quest-summary.component.ts
@Component({
moduleId: module.id,
selector: 'quest-summary',
templateUrl: 'quest-summary.component.html',
styleUrls: ['quest-summary.component.css']
})
export class QuestSummaryComponent { }