Universal: JavaScript code that can execute on the client and the server.
What's available today...
...and what's coming (soon) in future versions.
https://github.com/angular/material2/issues/308
Browser types like window, document, and navigator do not
exist on the server.
If you need them, you can use the Object injected using the PLATFORM_ID token to
check whether the current platform is browser or server.
import { PLATFORM_ID } from '@angular/core';
import {
isPlatformBrowser,
isPlatformServer
} from '@angular/common';
constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
// Client only code.
}
if (isPlatformServer(this.platformId)) {
// Server only code.
}
}
Don't manipulate the nativeElement directly
Use the Renderer. This ensures that in any environment we're able to change our view.
constructor(element: ElementRef, renderer: Renderer) {
renderer.setElementStyle(element.nativeElement, 'font-size', 'x-large');
}
What about the CLI?
…but for now: https://github.com/FrozenPandaz/ng-universal-demo
Builds on the TOH tutorial.
app.engine('html', ngExpressEngine({
bootstrap: ServerAppModule
}));
@NgModule({
...
imports: [
BrowserModule.withServerTransition({
appId: 'my-app-id'
}),
...
]
})
export class ServerAppModule { }
Defines a shared id so that the client-side Angular app can replace the DOM rendered on the server during application bootstrap.
Write data into the document so that it can be read by the client-side Angular app.
window['TRANSFER_STATE']