Search code examples
angularboilerplatengoninit

Angular - Common ngOnInit


If I have in every component

ngOnInit() {
  console.log('hello world');
}

How do I avoid writing that code in each component? Can I write some common code that will trigger onInit for each component, maybe in their module? Or in their shared service they all use, for example?

I have the same question about NavigationStart and NavigationEnd.

Thx


Solution

  • The easiest way to do it is by extending from the base component:

    @Component({
        selector: 'base-component',
        template: '',
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class BaseComponent implements OnInit {
    
     ngOnInit (): void {
      console.log('hello world');
     }
    }
    

    and use extends BaseComponent in your child components, for example:

    @Component({
        selector: 'child-component',
        template: '',
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class ChildComponent extends BaseComponent {
      // your logic
    }
    

    Another way: using service with a local provider for each component:

    @Injectable()
    export class ActionService {
     constructor(){
       console.log('hello world');
     }
    }
    

    and inject it (providers: [ActionService]) to your component which has to has this logic, each component will have a separate instance of this service:

    @Component({
        selector: 'main-page',
        templateUrl: './main-page.component.html',
        styleUrls: ['./main-page.component.scss'],
        changeDetection: ChangeDetectionStrategy.OnPush,
        providers: [ActionService]
    })
    export class MainPageComponent {}
    

    as for me: the first solution much better than providing service each time, but it's up to you :)