Angular component inheritance. How parent's life cycle hooks can be executed?

Viewed 4543

So I have BaseComponent and many childs extends it:

export class Child1Component extends BaseComponent implements OnInit, AfterViewInit

Child1Component does not call super.ngAfterViewInit(), but for some reason BaseComponent AfterViewInit is executed. I just console it log:

ngAfterViewInit() {
  console.log('BaseComponent AfterViewInit')
}

How is that possible? What else except of super.ngAfterViewInit() can call parent's life cycle hook?

Could this be happening only in development mode?

3 Answers

I think it's normal OOP inheritance behaviour. If you don't explicitly define the ngAfterViewInit on the child component, then this component will have the the parent implementation of that method available.

So, during components lifecycle, when angular checks wether the ngAfterViewInit method is available on the child component, then the answser is yes: the child component has that method implemented, but it's inherited from the parent component

the child componenet will have (inherent) all base component class property and method so normally the child class will have ngAfterViewInit method and this will run by angular ,in case you want to overwrite this method simplly recreate this at the child class and this will take present over the method in the base class , but even you can access to the base class by using super keyword

export class Child1Component extends BaseComponent implements OnInit, AfterViewInit {

  ngAfterViewInit() {
    super.ngAfterViewInit(); //  call base ngAfterViewInit method  
    console.log('Child1Component AfterViewInit');
  }

}

ngAfterViewInit is special method it one of lifecycle hooks a method run and manage by angular , read more about this here

From the Docs:

ngAfterViewInit()

Respond after Angular initializes the component's views and child views / the view that a directive is in.

Called once after the first ngAfterContentChecked().

As you can see that its the normal behavior in case of ngAfterViewInit()

Related