5

Maybe the answer to this question is relevant for AngularJS (1.x) also, but my question here is for Angular 2 and above.

As we know, every component file has its own ngOnInit function, which runs the code inside of it when the component initializes. In my current application, I need to run the same piece of code in ALL these functions, in ALL the components, and automatically. Right now, I just copy the code between these functions, for each component's TS file. Is there a way of putting this code once in a common place and have all these init functions run it from there, automatically? Meaning, even brand new components added to the app will run this code, as part of their init function...

TheCuBeMan
  • 1,954
  • 4
  • 23
  • 35

1 Answers1

6

Components are classes and as such can extend (abstract) base classes, example code:

BaseClass:

export abstract class AppBaseComponent implements OnInit {
constructor() { }
  ngOnInit() {
    // Your base code here
  }

}

Extending classes

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends AppBaseComponent implements OnInit {
  constructor() {
    super();
  }
  // Your component specific code here
}
Jens Habegger
  • 5,266
  • 41
  • 57
  • 2
    Instead of extending a base class (like in Jens's answer) you could also do the Aspect-Oriented-Programming approach and define own decorators with typescript. Check out this tutorial: https://www.meziantou.net/2018/01/11/aspect-oriented-programming-in-typescript – Phil May 08 '18 at 13:10
  • @JensHabegger - first of all, thanks for this info!! I have 2 questions about your answer here, though: 1. by this example, the code that exists under the ngOnInit function of the base component will run automatically also when the AppComponent runs? 2. What happens if I want to extend the AppComponent to more than one other component? By this example, let's say I need to run code both from the base component and some other one in the app... – TheCuBeMan May 09 '18 at 05:10
  • @TheCuBeMan Typescript does not (yet) support multiple inheritance, but you can either check out the pattern Phil suggested (Aspect Oriented Programming) or use Typescript Mixins (https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-mix-in-classes). – Jens Habegger May 09 '18 at 05:23