Created
November 25, 2021 13:32
-
-
Save eneajaho/558f8480237ede41cf9c03d47781628b to your computer and use it in GitHub Desktop.
Server/Client side only - Angular Directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Show only on server-side:
Show only on client-side: