组件创建
在所要创建的文件夹下,运行ng generate component component-overview
是组建的名称。
创建结束后出现
- 一个以该组件命名的文件夹
- 一个组件文件 .component.ts
- 一个模板文件 .component.html
- 一个 CSS 文件, .component.css
- 测试文件 .component.spec.ts
组件模板定义
在component-overview.component.ts
中
import { Component, OnInit } from '@angular/core';
@Component({
// 指定css选择器:添加一个 selector 语句来指定组件的选择器。
selector: 'app-component-overview',
// 可以通过以下两种方式之一为组件定义模板:
// 引用外部文件,或直接写在组件内部。
// 要把模板定义为外部文件,就要把 templateUrl 添加到 @Component 装饰器中。
templateUrl: './component-overview.component.html',
// 在组件中定义模板,就要把一个 template 属性添加到 @Component 中,
// 该属性的内容是要使用的 HTML。
// template:'<h1>组建中定义模板</h1>',
// 模板跨越多行,你可以使用反引号( ` )
// template: `<h1>Hello World!</h1>
// <p>This template definition spans
// multiple lines.</p>`,
styleUrls: ['./component-overview.component.css']
})
export class ComponentOverviewComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
声明组件样式
有两种方式来为组件的模板声明样式:引用一个外部文件,或直接写在组件内部。
要在单独的文件中声明组件的样式,就要把 styleUrls
属性添加到 @Component
装饰器中。
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
要想在组件内部声明样式,就要把 styles
属性添加到 @Component
,该属性的内容是你要用的样式。
@Component({
selector: 'app-component-overview',
template: '<h1>Hello World!</h1>',
styles: ['h1 { font-weight: normal; }']
})
拜