Class 如何控制Angular 2中扩展类实例的生命周期
在Angular 2.4.9中,以下代码不适用于我:Class 如何控制Angular 2中扩展类实例的生命周期,class,angular,extend,Class,Angular,Extend,在Angular 2.4.9中,以下代码不适用于我: export class MyComponent extends BaseComponent implements OnInit { type = 2; constructor() { super(); } ngOnInit(){ console.log('inited type', this.type) } } 含义:没有控制台输出-无论BaseComponent是否实现OnInit 如果BaseC
export class MyComponent extends BaseComponent implements OnInit {
type = 2;
constructor() {
super();
}
ngOnInit(){
console.log('inited type', this.type)
}
}
含义:没有控制台输出-无论BaseComponent
是否实现OnInit
如果BaseComponent
实现了钩子,那么只调用它的钩子,而不是在MyComponent
上重写的钩子
讨论证明了我描述的plunker实际上是有效的,我成功地将我的问题复制到了
有没有办法在扩展类中使用生命周期挂钩?问题是您的
类型从来没有设置过,因此您的*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>
修复了plunker:您是否在任何地方使用该组件?我在页面上使用MyComponent。在这里工作正常:谢谢@echonax。你证明了我的计划没有解决实际问题。请查看重现我问题的plnkr链接。是的,的确,在plnkr中我忘记了实际实现输入,但在我的应用程序中,我实际上忘记了在html中括起来。顺便说一句,这是实现我在这里想要实现的目标的最佳方式吗,即根据输入动态切换html模板?@nuton因为组件中实际上什么都没有,很难说:-)如果功能相同,也许你可以查看ngSwitchCase
指令。我在我的应用程序中实际使用了ngSwitchCase
(ngIf
在这里使用是为了简洁)。“我只是想知道是否有人能以某种方式使用TemplateRef。”纳顿很高兴我回答了你的问题。对我来说,这是一个提示和技巧部分:P
@Input() public type: number;