Angular 的核心构建块是 组件(Components),它是实现用户界面的基本单元。每个组件通常包含模板(HTML)、逻辑(TypeScript)和样式(CSS)三部分。
组件核心概念
- 组件类:通过
@Component
装饰器定义,包含选择器、模板URL、样式等元数据 - 模板:使用 HTML 和 Angular 模板语法(如
{{ }}
、*ngIf
)构建 UI - 数据绑定:支持双向绑定(
[(ngModel)]
)和属性绑定([attr.aria-label]
) - 事件处理:通过
(click)
、(input)
等语法监听用户交互
组件生命周期
Angular 组件有 8 个生命周期钩子(Lifecycle Hooks):
ngOnChanges
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngOnDestroy
常用组件类型
类型 | 说明 | 示例 |
---|---|---|
@Component |
声明组件 | @Component({ selector: 'app-root' }) |
@Directive |
创建自定义指令 | @Directive({ selector: 'my-button' }) |
@Pipe |
实现数据转换 | `{{ name |
实战示例
创建一个简单组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>欢迎使用 Angular!</p>`,
styleUrls: ['./example.component.css']
})
export class ExampleComponent { }
扩展阅读
想深入了解 Angular 的高级组件用法?
点击这里查看 Angular 模板与样式指南 ✅
📌 提示:组件是 Angular 应用的基石,建议结合 Angular 官方文档 深入学习。