Angular 生命周期钩子是一组可在组件生命周期中执行的方法,用于在特定时间点执行特定操作。以下是一些常用的 Angular 生命周期钩子及其对应的代码示例:
import { Component, Input, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-example',
template: '{{name}}
'
})
export class ExampleComponent {
@Input() name: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Input property changed:', changes.name.currentValue);
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: '{{message}}
'
})
export class ExampleComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Hello, Angular!';
console.log('Component initialized');
}
}
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
template: ''
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('btn') button: ElementRef;
ngAfterViewInit() {
this.button.nativeElement.addEventListener('click', () => {
console.log('Button clicked');
});
}
}
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: 'Example component
'
})
export class ExampleComponent implements OnDestroy {
ngOnDestroy() {
console.log('Component destroyed');
}
}
这些是一些常用的 Angular 生命周期钩子及其对应的代码示例。根据具体的需求,你可以选择适当的钩子来执行相应的操作。