在angular中,可以使用命令创建组件
命令如下
ng generate component <component-name>
命令中<component-name>
为需要创建的组件的名称
创建成功后,组件文件结构如下:
test-component.component.html
为需要显示信息的html模板。内容如下:
test-component.component.less
为css模板,我在创建项目时选用的是less,所以创建的为less文件。
test-component.component.spec.ts
文件用于对Angular服务,组件等进行单元测试,是我在创建应用是选择了测试模块吗?也许是错误的,由于我也是第一次接触,也不清楚。
test-component.component.ts
里面包含了组件的信息,方法,生命周期等。
在test-component.component.ts
中,部分写法及含义如下:
import { Component, OnInit } from '@angular/core';
// @Component修饰器
@Component({
// css选择器 可以理解为在html中使用该组件的标签
selector: 'app-test-component',
// 用于显示信息的html模板 两种方式:1.写在组件内部 2.链接指向外部文件
// 1.
// template: `<h1>Hello World!</h1>
// <p>This template definition spans
// multiple lines.</p>`,
// 2.
templateUrl: './test-component.component.html',
// html模板的样式文件 同html模板一样
// 1.styles 属性接受一个包含 CSS 规则的字符串数组
// styles: ['h1 { font-weight: normal; }'],
// 2.
styleUrls: ['./test-component.component.less']
})
export class TestComponentComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}