Skip to content

Instantly share code, notes, and snippets.

@eneajaho
Created November 25, 2021 13:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneajaho/558f8480237ede41cf9c03d47781628b to your computer and use it in GitHub Desktop.
Save eneajaho/558f8480237ede41cf9c03d47781628b to your computer and use it in GitHub Desktop.
Server/Client side only - Angular Directive
import { Directive, Inject, NgModule, OnInit, PLATFORM_ID, TemplateRef, ViewContainerRef } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
/**
* Add the template content to the DOM based on platform
*/
@Directive({ selector: '[serverSideOnly]' })
export class ServerSideOnlyDirective implements OnInit {
constructor(
@Inject(PLATFORM_ID) private platformId: string,
private templateRef: TemplateRef<any>,
private vcr: ViewContainerRef
) { }
ngOnInit(): void {
if (isPlatformServer(this.platformId)) {
this.vcr.createEmbeddedView(this.templateRef);
} else {
this.vcr.clear();
}
}
}
@Directive({ selector: '[clientSideOnly]' })
export class ClientSideOnlyDirective implements OnInit {
constructor(
@Inject(PLATFORM_ID) private platformId: string,
private templateRef: TemplateRef<any>,
private vcr: ViewContainerRef
) { }
ngOnInit(): void {
if (isPlatformBrowser(this.platformId)) {
this.vcr.createEmbeddedView(this.templateRef);
} else {
this.vcr.clear();
}
}
}
@NgModule({
declarations: [ ServerSideOnlyDirective, ClientSideOnlyDirective ],
exports: [ ServerSideOnlyDirective, ClientSideOnlyDirective ]
})
export class ServerClientSideOnlyModule { }
@eneajaho
Copy link
Author

Usage:

Show only on server-side:

<ng-container *serverSideOnly>
  Shown only on server (node server)
</ng-container>

Show only on client-side:

<ng-container *clientSideOnly>
  Shown only on client (web browser)
</ng-container>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment