如何为 Angular2 组件实现多个生命周期钩子?
How to implement multiple lifecycle hooks for an Angular2 component?
我知道在 Angular2 中定义组件时,您可以实现多种类型的生命周期挂钩,例如 OnDestroy、NgOnInit 等。
在我在网上看到的关于使用这些钩子的每一段示例代码中,我一次只看到它们被使用了一个。例如
export class ModalComponent implements OnDestroy { ... }
或
export class ModalComponent implements OnChanges { ... }
但是如果你想对单个组件使用多个怎么办?例如,如果您想要 OnChanges 和 OnDestroy 的特定行为怎么办?我尝试了以下方法:
export class ModalComponent implements OnChanges implements OnDestroy{ ... }
export class ModalComponent implements OnChanges, OnDestroy { ... }
export class ModalComponent implements [OnChanges, OnDestroy] { ... }
export class ModalComponent implements OnChanges and OnDestroy { ... }
我确定答案很简单,但我很难找到答案。
提前致谢!
您可以扩展 1 class 并实现多个接口。生命周期挂钩是接口。
class D extends C implements A, B{}
当您使用逗号分隔符实现两个接口时,您可能是对的。
这是一个例子。
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-ram-component',
templateUrl: './ram.component.html',
styleUrls: ['./ram.component.css']
})
export class RamComponentComponent implements OnInit,OnDestroy,AfterViewInit {
constructor() { }
ngOnInit() {
console.log('On Init');
}
ngAfterViewInit(){
console.log('after view');
}
ngOnDestroy(){
console.log('destroyed!!');
}
}
请注意导入语句必须包含所有必要的生命周期挂钩。
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
我知道在 Angular2 中定义组件时,您可以实现多种类型的生命周期挂钩,例如 OnDestroy、NgOnInit 等。
在我在网上看到的关于使用这些钩子的每一段示例代码中,我一次只看到它们被使用了一个。例如
export class ModalComponent implements OnDestroy { ... }
或
export class ModalComponent implements OnChanges { ... }
但是如果你想对单个组件使用多个怎么办?例如,如果您想要 OnChanges 和 OnDestroy 的特定行为怎么办?我尝试了以下方法:
export class ModalComponent implements OnChanges implements OnDestroy{ ... }
export class ModalComponent implements OnChanges, OnDestroy { ... }
export class ModalComponent implements [OnChanges, OnDestroy] { ... }
export class ModalComponent implements OnChanges and OnDestroy { ... }
我确定答案很简单,但我很难找到答案。
提前致谢!
您可以扩展 1 class 并实现多个接口。生命周期挂钩是接口。
class D extends C implements A, B{}
当您使用逗号分隔符实现两个接口时,您可能是对的。
这是一个例子。
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-ram-component',
templateUrl: './ram.component.html',
styleUrls: ['./ram.component.css']
})
export class RamComponentComponent implements OnInit,OnDestroy,AfterViewInit {
constructor() { }
ngOnInit() {
console.log('On Init');
}
ngAfterViewInit(){
console.log('after view');
}
ngOnDestroy(){
console.log('destroyed!!');
}
}
请注意导入语句必须包含所有必要的生命周期挂钩。
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';