1. ngOnInit
- 用途:用于在组件初始化后执行逻辑。通常用于初始化数据,如从服务获取数据并填充到组件属性中。比如在一个用户信息展示组件中,从用户服务获取用户详细信息并展示。
- 示例:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-user',
templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {
user: any;
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUser().subscribe(data => {
this.user = data;
});
}
}
2. ngOnChanges
- 用途:当组件的输入属性(
@Input()
)值发生变化时调用。常用于根据输入值的变化来重新计算或更新组件的状态。例如,在一个根据传入的商品ID展示商品详情的组件中,当商品ID改变时,重新获取新商品的详情。
- 示例:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html'
})
export class ProductDetailComponent implements OnChanges {
@Input() productId: number;
product: any;
constructor(private productService: ProductService) {}
ngOnChanges(changes: SimpleChanges) {
if (changes.productId) {
this.productService.getProduct(changes.productId.currentValue).subscribe(data => {
this.product = data;
});
}
}
}
3. ngDoCheck
- 用途:用于自定义变更检测。Angular默认的变更检测机制无法检测到的一些变化,比如对象内部属性的变化,可在此钩子函数中手动处理。但由于频繁调用可能影响性能,需谨慎使用。例如,监控一个复杂对象内部某个深层属性的变化。
- 示例:
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-custom-check',
templateUrl: './custom-check.component.html'
})
export class CustomCheckComponent implements DoCheck {
complexObject: { subObject: { value: number } } = { subObject: { value: 0 } };
ngDoCheck() {
const previousValue = this.complexObject.subObject.value;
// 模拟复杂对象内部属性变化检测
if (previousValue!== this.complexObject.subObject.value) {
console.log('Complex object internal value has changed');
}
}
}
4. ngAfterContentInit
- 用途:当组件的内容(
ng-content
)投影完成后调用。常用于对投影到组件内的内容进行初始化操作。比如,在一个包含自定义列表项的列表组件中,对列表项进行样式或行为的初始化。
- 示例:
<!-- list.component.html -->
<ul>
<ng-content></ng-content>
</ul>
import { Component, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-list',
templateUrl: './list.component.html'
})
export class ListComponent implements AfterContentInit {
ngAfterContentInit() {
console.log('List content has been initialized');
// 可以在这里操作投影进来的列表项DOM等
}
}
5. ngAfterContentChecked
- 用途:在组件内容投影完成且变更检测后调用。用于检测投影内容的变化,可进行相应的处理。例如,当投影内容中的数据发生变化时,更新组件的某些统计信息。
- 示例:
import { Component, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-content-check',
templateUrl: './content-check.component.html'
})
export class ContentCheckComponent implements AfterContentChecked {
itemCount = 0;
ngAfterContentChecked() {
// 假设投影内容是列表项,重新计算列表项数量
this.itemCount = // 获取投影内容中列表项数量的逻辑
console.log('Content has been checked, item count:', this.itemCount);
}
}
6. ngAfterViewInit
- 用途:当组件的视图(包括子视图)初始化完成后调用。适合进行需要访问视图元素的操作,如操作DOM、初始化第三方UI库等。例如,初始化一个基于DOM的图表库。
- 示例:
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html'
})
export class ChartComponent implements AfterViewInit {
@ViewChild('chartCanvas') chartCanvas;
chart: any;
ngAfterViewInit() {
this.chart = new Chart(this.chartCanvas.nativeElement, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
7. ngAfterViewChecked
- 用途:在组件视图(包括子视图)变更检测后调用。可用于响应视图变化,例如在视图变化后重新调整某些元素的布局。但频繁操作可能影响性能。
- 示例:
import { Component, AfterViewChecked } from '@angular/core';
@Component({
selector: 'app-layout-check',
templateUrl: './layout-check.component.html'
})
export class LayoutCheckComponent implements AfterViewChecked {
ngAfterViewChecked() {
// 假设存在一个需要根据窗口大小调整位置的元素
const element = document.getElementById('special-element');
if (element) {
if (window.innerWidth < 600) {
element.style.position = 'fixed';
element.style.bottom = '10px';
} else {
element.style.position = 'static';
}
}
}
}
8. ngOnDestroy
- 用途:在组件销毁前调用。常用于清理工作,如取消订阅可观察对象以避免内存泄漏,销毁定时器等。例如,在一个使用了
Observable
来实时获取数据的组件中,在组件销毁时取消订阅。
- 示例:
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from './data.service';
@Component({
selector: 'app-live-data',
templateUrl: './live-data.component.html'
})
export class LiveDataComponent implements OnDestroy {
data: any;
subscription: Subscription;
constructor(private dataService: DataService) {
this.subscription = this.dataService.getData().subscribe(data => {
this.data = data;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}