Search code examples
angulartypescript

Angular life-cycle events call without implementing interface?


I am working with angular application and I found that angular life cycle events is call without implement interface.In below example if i remove interface from component then all the angular life-cycle hooks is working fine. My question about without implement interface why angular is call all the events?

I know in typescript we can use all OOP concepts that we can use with c#.

life-cycle.component.ts

import {
  Component,
  OnInit,
  OnChanges,
  SimpleChanges,
  Input,
  AfterViewInit,
  DoCheck,
  AfterViewChecked,
  AfterContentChecked,
  AfterContentInit,
  OnDestroy
} from '@angular/core';

@Component({
  selector: 'app-life-cycle',
  templateUrl: './life-cycle.component.html',
  styleUrls: ['./life-cycle.component.css']
})
export class LifeCycleComponent
  implements
    OnChanges,
    OnInit,
    DoCheck,
    AfterViewInit,
    AfterViewChecked,
    AfterContentChecked,
    AfterContentInit,
    OnDestroy {
  @Input('appTitle') appTitle: string;
  constructor() {
    console.log('constructor called!');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called!');
    console.log(changes);
  }
  ngOnInit() {
    console.log('ngOnInit called!');
  }

  ngDoCheck() {
    console.log('ngDoCheck called!');
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit called!');
  }
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked called!');
  }
  ngAfterContentInit() {
    console.log('ngAfterContentInit called!');
  }
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked called!');
  }
  ngOnDestroy() {
    //console.log('ngOnDestroy called!');
  }
}

life-cycle.component.html

<p>
  life-cycle works!
</p>

Solution

  • The use of the Angular lifecycle interfaces is optional. They just help you as a developer.

    Technically, TypeScript is compiled to JavaScript, which doesn't have interfaces. Angular just calls the JavaScript Lifecycle methods if they exist. That's the reason why it doesn't make any difference if you use the interfaces or not. (Source: Docs)

    Nevertheless, you should use the interfaces for multiple reasons: (Credits to @Nick)

    1. It is more clear which Lifecycle events are actually used. In big classes with many methods you quickly lose the overview. The use of the interfaces allow you to quickly determine all used Lifecycle methods in one place - at the beginning of the TypeScript Class.
    2. The TypeScript compiler warns you if you don't implement the Lifecycle methods correctly, for example if you forgot to implement the method, misspelled the method name or the method was accidentally removed.
    3. Angular recommends this in their styleguide.

    In case you are using @angular-eslint/eslint-plugin, you can enable the @angular-eslint/use-lifecycle-interface rule to enforce the use of the interfaces.