Angular 生命周期鉤子是在 Angular 組件的生命周期的不同階段自動調用的特殊方法。它們允許你在組件的不同階段執行代碼,例如初始化數據、訂閱服務、清理資源等。要使用生命周期鉤子,你需要在組件類中定義相應的方法。下面是一些常用的生命周期鉤子及其使用方法:
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements OnChanges {
@Input() data: any;
ngOnChanges(changes: SimpleChanges) {
console.log('Data changed:', changes);
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements OnInit {
constructor() {}
ngOnInit() {
console.log('Component initialized');
}
}
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
constructor() {}
ngOnDestroy() {
this.subscription.unsubscribe();
console.log('Component destroyed');
}
}
import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements AfterViewInit {
ngAfterViewInit() {
console.log('View initialized');
}
}
這些只是 Angular 生命周期鉤子的一部分。還有其他鉤子,如 ngBeforeViewInit、ngAfterContentInit、ngAfterContentChecked、ngBeforeContentChecked 等。你可以根據需要在組件類中實現這些鉤子。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。