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>
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)
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.