Angular 2+ - run same code on ALL ngOnInit automatically
Asked Answered
L

1

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...

Literally answered 8/5, 2018 at 12:50 Comment(0)
T
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
}
Tiny answered 8/5, 2018 at 12:59 Comment(3)
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: meziantou.net/2018/01/11/…Animalcule
@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...Literally
@Literally Typescript does not (yet) support multiple inheritance, but you can either check out the pattern Phil suggested (Aspect Oriented Programming) or use Typescript Mixins (github.com/Microsoft/TypeScript/wiki/…).Tiny

© 2022 - 2024 — McMap. All rights reserved.