如何控制 Angular 中扩展 class 实例的生命周期 2
How can I control lifecycle of extended class instances in Angular 2
在 Angular 2.4.9 中,下面的代码对我不起作用:
export class MyComponent extends BaseComponent implements OnInit {
type = 2;
constructor() {
super();
}
ngOnInit(){
console.log('inited type', this.type)
}
}
意思是:没有控制台输出——不管 BaseComponent
是否实现了 OnInit
。
如果 BaseComponent
实现了钩子,那么只有它的钩子被调用,而不是 MyComponent
上的覆盖钩子。
由于讨论证明与我的描述一起创建的 plunker 确实有效,我设法在 this plunkr 中重现了我的问题。
有没有办法在扩展的class中使用生命周期钩子?
问题是您的 type
从未设置,因此您的 *ngIf
无法正常工作。
根据您提供的 plunker,您需要在 @Input
中提供类型
应用模板
<base-comp [type]="1"></base-comp>
<base-comp [type]="2"></base-comp>
<base-comp [type]="1"></base-comp>
<base-comp [type]="2"></base-comp>
基础组件字段
@Input() public type: number;
在 Angular 2.4.9 中,下面的代码对我不起作用:
export class MyComponent extends BaseComponent implements OnInit {
type = 2;
constructor() {
super();
}
ngOnInit(){
console.log('inited type', this.type)
}
}
意思是:没有控制台输出——不管 BaseComponent
是否实现了 OnInit
。
如果 BaseComponent
实现了钩子,那么只有它的钩子被调用,而不是 MyComponent
上的覆盖钩子。
由于讨论证明与我的描述一起创建的 plunker 确实有效,我设法在 this plunkr 中重现了我的问题。
有没有办法在扩展的class中使用生命周期钩子?
问题是您的 type
从未设置,因此您的 *ngIf
无法正常工作。
根据您提供的 plunker,您需要在 @Input
应用模板
<base-comp [type]="1"></base-comp>
<base-comp [type]="2"></base-comp>
<base-comp [type]="1"></base-comp>
<base-comp [type]="2"></base-comp>
基础组件字段
@Input() public type: number;