Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 522
bigInt Avatar asked Jun 19 '19 12:06

bigInt


People also ask

Are lifecycle hooks inherited?

Lifecycle methods are not inherited Lifecycle methods (OnInit, OnChanges, …) are not inherited by the child components.

Which of the following method is executed at last during component life cycle?

This method called after ngAfterContentInit() method. This method is also called on every subsequent execution of ngDoCheck(). This method is also mainly linked with the child component initializations. This lifecycle hook method executes when the component's view has been fully initialized.

What is the life cycle hook called by Angular During the component initialization?

ngOnChanges This is one of the lifecycle hooks which can come in handy in multiple use cases. It is very useful if you need to handle any specific logic in the component based on the received input property.


2 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

like image 139
David Avatar answered Sep 19 '22 07:09

David


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

like image 41
Muhammed Albarmavi Avatar answered Sep 19 '22 07:09

Muhammed Albarmavi