Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement multiple lifecycle hooks for an Angular2 component?

I know that when defining components in Angular2 you have multiple types of lifecycle hooks that you can implement such as OnDestroy, NgOnInit, etc.

In every sample piece of code I've seen online about using these hooks, I only ever see them being used one at a time. For instance

export class ModalComponent implements OnDestroy { ... }

or

export class ModalComponent implements OnChanges { ... } 

But what if you want to use multiple for a single component? For instance, what if you want specific behavior for OnChanges AND OnDestroy? I've tried the following:

export class ModalComponent implements OnChanges implements OnDestroy{ ... } 
export class ModalComponent implements OnChanges, OnDestroy { ... } 
export class ModalComponent implements [OnChanges, OnDestroy] { ... } 
export class ModalComponent implements OnChanges and OnDestroy { ... } 

I'm certain the answer is very simple but I'm having a remarkable amount of trouble finding an answer to this.

Thank you in advance!

like image 627
SemperCallide Avatar asked Jan 10 '17 22:01

SemperCallide


People also ask

How many lifecycle hooks are available in Angular?

Angular gives us 8 hooks to allow us to tap into the lifecycle of our components and trigger actions at specific points in the lifecycle.

Can we implement multiple interfaces in Angular?

You can extend 1 class and implement multiple interfaces.

What is the possible order of lifecycle hooks?

The sequence of log messages follows the prescribed hook calling order: OnChanges , OnInit , DoCheck (3x), AfterContentInit , AfterContentChecked (3x), AfterViewInit , AfterViewChecked (3x), and OnDestroy .


2 Answers

You can extend 1 class and implement multiple interfaces. Lifecycle hooks are interfaces.

class D extends C implements A, B{}
like image 138
A. Tim Avatar answered Oct 17 '22 16:10

A. Tim


You were probably right when you implemented two interfaces with a comma separator.

Here's an example.

import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';


@Component({
  selector: 'app-ram-component',
  templateUrl: './ram.component.html',
  styleUrls: ['./ram.component.css']
})

export class RamComponentComponent implements OnInit,OnDestroy,AfterViewInit { 

  constructor() { }

  ngOnInit() {
    console.log('On Init');
  }
  ngAfterViewInit(){
    console.log('after view');
  }
  ngOnDestroy(){
    console.log('destroyed!!');
  }
}

Please note the import statement has to include all the necessary lifecycle hooks.

 import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';

Lifecycle Hooks Reference

like image 42
Ram Kishore K Avatar answered Oct 17 '22 16:10

Ram Kishore K