Angular生命周期钩子参数指的是在组件的生命周期中,可以使用的参数。每个生命周期钩子都可以接收特定的参数,用于在特定的生命周期阶段执行一些操作。
以下是一些常用的Angular生命周期钩子和示例代码:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-example',
template: '{{name}}
'
})
export class ExampleComponent implements OnChanges {
@Input() name: string;
ngOnChanges(changes: SimpleChanges) {
console.log(changes.name.currentValue); // 输出输入属性的新值
console.log(changes.name.previousValue); // 输出输入属性的旧值
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: '{{message}}
'
})
export class ExampleComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Hello, Angular!';
}
}
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';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: '{{message}}
'
})
export class ExampleComponent implements OnDestroy {
message: string;
subscription: Subscription;
constructor() {
this.subscription = someObservable.subscribe((data) => {
this.message = data;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
这些是一些常用的Angular生命周期钩子和示例代码。根据实际需求,可以选择适合的生命周期钩子,并使用相应的参数进行操作。