This rule raises an issue when Angular lifecycle methods are implemented in classes where they won’t be called by the framework.
Angular lifecycle methods are only called by the framework in specific contexts. Each decorator type (@Component, @Directive, @Injectable, @NgModule, @Pipe) supports different lifecycle methods.
Using lifecycle methods in the wrong context creates several problems:
For example, view-related lifecycle methods like ngAfterViewInit only work in Components and Directives that have templates. Using
them in Services or Pipes is meaningless since these don’t have views.
The code will not behave as expected since the lifecycle methods won’t be called. This can lead to initialization logic not running, cleanup not happening, or change detection not working properly. It may also confuse team members about the application’s behavior.
Remove lifecycle methods that are not supported in the current context, or move the logic to an appropriate lifecycle method or initialization pattern.
@Injectable()
class UserService {
ngOnInit() { // Noncompliant - Services don't support ngOnInit
this.loadUsers();
}
ngAfterViewInit() { // Noncompliant - Services don't have views
console.log('View initialized');
}
}
@Injectable()
class UserService {
constructor() {
this.loadUsers(); // Use constructor for initialization
}
ngOnDestroy() { // Only ngOnDestroy is supported in services
this.cleanup();
}
}
Use ngDoBootstrap only in NgModule classes, not in Components or other contexts.
@Component({
selector: 'app-root',
template: '<div>App</div>'
})
class AppComponent {
ngDoBootstrap() { // Noncompliant - Components don't support ngDoBootstrap
console.log('Bootstrapping');
}
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule]
})
class AppModule {
ngDoBootstrap() { // Correct - NgModules support ngDoBootstrap
console.log('Bootstrapping');
}
}