Skip to content

Commit 9f09cb5

Browse files
atarix83Andrea Barbasso
authored andcommitted
[DURACOM-248] Create structural directive for rendering elements on browser only
(cherry picked from commit 74a53b7)
1 parent 8c3bd3f commit 9f09cb5

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { isPlatformBrowser } from '@angular/common';
2+
import {
3+
ChangeDetectorRef,
4+
Directive,
5+
Inject,
6+
OnInit,
7+
PLATFORM_ID,
8+
TemplateRef,
9+
ViewContainerRef,
10+
} from '@angular/core';
11+
12+
@Directive({
13+
selector: '[dsRenderOnlyForBrowser]',
14+
standalone: true,
15+
})
16+
/**
17+
* Structural Directive for rendering a template reference on client side only
18+
*/
19+
export class BrowserOnlyDirective implements OnInit {
20+
21+
constructor(
22+
@Inject(PLATFORM_ID) protected platformId: string,
23+
private viewContainer: ViewContainerRef,
24+
private changeDetector: ChangeDetectorRef,
25+
private templateRef: TemplateRef<any>,
26+
) {
27+
}
28+
29+
ngOnInit(): void {
30+
this.showTemplateBlockInView();
31+
}
32+
33+
/**
34+
* Show template in view container according to platform
35+
*/
36+
private showTemplateBlockInView(): void {
37+
if (!this.templateRef) {
38+
return;
39+
}
40+
this.viewContainer.clear();
41+
42+
if (isPlatformBrowser(this.platformId)) {
43+
this.viewContainer.createEmbeddedView(this.templateRef);
44+
this.changeDetector.markForCheck();
45+
}
46+
}
47+
48+
}

0 commit comments

Comments
 (0)