Created
July 8, 2018 20:14
-
-
Save arutnik/4ce3b55404daa63db5e47d0d2782f13b to your computer and use it in GitHub Desktop.
SEO-SPA: If Platform 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, Input, TemplateRef, ViewContainerRef, PLATFORM_ID, Inject } from '@angular/core'; | |
import { isPlatformServer, isPlatformBrowser } from '@angular/common'; | |
/** | |
* Adds the template content to the DOM only if the platform is the requested platform | |
* | |
* Usage to make a component only visible on client renders: | |
* <div *ifPlatform="'browser'">....</div> | |
* | |
* Usage to make a component only visible on server renders: | |
* <div *ifPlatform="'server'">...</div> | |
*/ | |
@Directive({ | |
selector: '[ifPlatform]' | |
}) | |
export class IfPlatformDirective { | |
private hasView = false; | |
constructor( | |
private templateRef: TemplateRef<any>, | |
private viewContainer: ViewContainerRef, | |
@Inject(PLATFORM_ID) private platformId: Object, | |
) { } | |
@Input() set ifPlatform(platform: 'browser' | 'server') { | |
let satisfied = (platform == 'browser' && this.isBrowserMode) | |
|| (platform == 'server' && this.isServerMode); | |
if (satisfied && !this._hasView) { | |
this.viewContainer.createEmbeddedView(this.templateRef); | |
this.hasView = true; | |
} else if (!satisfied && this.hasView) { | |
this.viewContainer.clear(); | |
this.hasView = false; | |
} | |
} | |
get isServerMode(): boolean { | |
return isPlatformServer(this.platformId); | |
} | |
get isBrowserMode(): boolean { | |
return isPlatformBrowser(this.platformId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment