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>
Called before ngOnInit() (if the component has bound inputs) and whenever one or more data-bound input properties change. NOTE: If your component has no inputs or you use it without providing any inputs, the framework will not call ngOnChanges() .
OnInit. OnInit is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive.
ngOnInit() is still called even when ngOnChanges() is not, which is the case when there are no template-bound inputs. This is one of the most used lifecycle hooks in Angular.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With