-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathdeferred-content.ts
More file actions
84 lines (76 loc) · 2.11 KB
/
deferred-content.ts
File metadata and controls
84 lines (76 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
afterRenderEffect,
Directive,
inject,
TemplateRef,
signal,
ViewContainerRef,
model,
EmbeddedViewRef,
OnDestroy,
} from '@angular/core';
/**
* A container directive controls the visibility of its content.
*/
@Directive()
export class DeferredContentAware {
readonly contentVisible = signal(false);
readonly preserveContent = model(false);
}
/**
* DeferredContent loads/unloads the content based on the visibility.
* The visibilty signal is sent from a parent directive implements
* DeferredContentAware.
*
* Use this directive as a host directive. For example:
*
* ```ts
* @Directive({
* selector: 'ng-template[AccordionContent]',
* hostDirectives: [DeferredContent],
* })
* class AccordionContent {}
* ```
*/
@Directive()
export class DeferredContent implements OnDestroy {
private readonly _deferredContentAware = inject(DeferredContentAware, {optional: true});
private readonly _templateRef = inject(TemplateRef);
private readonly _viewContainerRef = inject(ViewContainerRef);
private _currentViewRef: EmbeddedViewRef<unknown> | null = null;
private _isRendered = false;
readonly deferredContentAware = signal(this._deferredContentAware);
constructor() {
afterRenderEffect({
write: () => {
if (this.deferredContentAware()?.contentVisible()) {
if (!this._isRendered) {
this._destroyContent();
this._currentViewRef = this._viewContainerRef.createEmbeddedView(this._templateRef);
this._isRendered = true;
}
} else if (!this.deferredContentAware()?.preserveContent()) {
this._destroyContent();
this._isRendered = false;
}
},
});
}
ngOnDestroy(): void {
this._destroyContent();
}
private _destroyContent() {
const ref = this._currentViewRef;
if (ref && !ref.destroyed) {
ref.destroy();
this._currentViewRef = null;
}
}
}