Search code examples
classangularextend

How can I control lifecycle of extended class instances in Angular 2


In Angular 2.4.9 this code below does not work for me:

export class MyComponent extends BaseComponent implements OnInit {
  type = 2;

  constructor() {
    super();
  }

  ngOnInit(){
    console.log('inited type', this.type)
  }
}

meaning: there's no console output - regardless of whether BaseComponent implements OnInit or not.

If BaseComponent implements the hook though, then only its hooks are called, not the overriden one on MyComponent.


As the discussion proved that the plunker created alongside my description actually works, I managed to reproduce my problem in this plunkr.


Is there any way to use lifecycle hooks in the extended class?


Solution

  • Problem is your type is never set so your *ngIf's are not working.

    According to the plunker you've provided, you need to provide the types in an @Input

    app template

    <base-comp [type]="1"></base-comp>
    <base-comp [type]="2"></base-comp>
    <base-comp [type]="1"></base-comp>
    <base-comp [type]="2"></base-comp>
    

    BaseComponent field

    @Input() public type: number;
    

    Fixed plunker: http://plnkr.co/edit/B4dFDR1bgLI5kGgGrozE?p=preview