3

For instance React's componentWillMount():

This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.

And in React's componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here.

However I do not see anything in the Angular doc specifying which ones are executed on the server and which ones are executed on the browser (or both). Or should I assume that all of them are executed on both? If so, how do you do things that require the DOM (window, document, etc.)?

David Barratt
  • 546
  • 1
  • 6
  • 24

1 Answers1

2

No, it doesn't. It runs the same hooks.

There's plenty of devices you can use to avoid contact with plain DOM, like HostBinding and HostListener decorators, Renderer and ElementRef classes. Remember that Angular 2 is a high-abstraction tool. It doesn't promotes access the DOM, although it is possible. Also, for server-side rendering, DI also comes to the rescue when there are different implementations for server and client.

Learn about Angular Universal to know more about server-side rendering at https://github.com/angular/universal.

If that doesn't answer your question, please place a more specific question.

André Werlang
  • 5,839
  • 1
  • 35
  • 49
  • I found this comment http://stackoverflow.com/a/35003208/864374 which is close to what I'm looking for, but on the server, the `useExisting: window` ... well `window` wouldn't exist, so what would happen? an Error? or could the dependency be optional? – David Barratt Feb 08 '17 at 19:42
  • ooo, I guess I could get the `ElementRef` https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html and then get the window off of the element? https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument and `ElementRef` should be `null` on the server right? – David Barratt Feb 08 '17 at 19:45
  • Make the dependency optional on injection, prepending it with `Optional()` – André Werlang Feb 08 '17 at 19:46
  • ok, great! If you want to update your answer to reference http://stackoverflow.com/questions/34177221/angular2-how-to-inject-window-into-an-angular2-service/35003208#35003208 with an `Optional()` because it seems like that's the best way to handle it. I assume all of the life cycle components will run _again_ on the browser after the server render? – David Barratt Feb 08 '17 at 20:51