Angular 的组件是构建用户界面的核心单元,每个组件包含模板(HTML)、逻辑(TypeScript)和样式(CSS)。以下是关键知识点:
1. 组件类型 🛠️
- 装饰器组件:使用
@Component
装饰器定义,如@Component({ selector: 'app-example', templateUrl: './example.component.html' }) export class ExampleComponent {}
- 嵌套组件:通过
@Component
的templateUrl
或template
属性实现
2. 生命周期钩子 💡
钩子名称 | 触发时机 | 示例 |
---|---|---|
ngOnChanges |
数据绑定变化时 | 检测输入属性变化 |
ngOnInit |
组件初始化后 | 执行初始化逻辑 |
ngOnDestroy |
组件销毁前 | 清理订阅 |
3. 最佳实践 ⚠️
- 避免在模板中直接写复杂逻辑
- 使用
@Input()
和@Output()
传递数据 - 查阅 Angular 官方组件指南 深入理解