This rule raises an issue when an Angular class defines lifecycle methods without implementing the corresponding lifecycle interfaces.
Angular provides lifecycle interfaces like OnInit, OnDestroy, and DoBootstrap that correspond to lifecycle
methods such as ngOnInit(), ngOnDestroy(), and ngDoBootstrap().
When a class implements lifecycle methods without the corresponding interfaces, several problems arise:
The Angular compiler and runtime will still work without the interfaces, but the code becomes less maintainable and more error-prone.
Without lifecycle interfaces, developers may accidentally implement lifecycle methods with incorrect signatures, leading to runtime issues where the methods are not called as expected. This can cause initialization logic to fail silently or cleanup code to not execute properly.
Import and implement the corresponding lifecycle interface for each lifecycle method in your class.
@Component()
class MyComponent {
ngOnInit() { // Noncompliant
console.log('Component initialized');
}
ngOnDestroy() { // Noncompliant
console.log('Component destroyed');
}
}
import { OnInit, OnDestroy } from '@angular/core';
@Component()
class MyComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
When extending a base class that already implements the interface, use the override keyword instead of implementing the interface
again.
@Component()
class BaseComponent implements OnInit {
ngOnInit() {
console.log('Base initialization');
}
}
@Component()
class DerivedComponent extends BaseComponent {
ngOnInit() { // Noncompliant
super.ngOnInit();
console.log('Derived initialization');
}
}
@Component()
class BaseComponent implements OnInit {
ngOnInit() {
console.log('Base initialization');
}
}
@Component()
class DerivedComponent extends BaseComponent {
override ngOnInit() {
super.ngOnInit();
console.log('Derived initialization');
}
}