-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathdeferred-content.ts
67 lines (63 loc) · 1.63 KB
/
deferred-content.ts
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
/**
* @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 {
computed,
Directive,
effect,
inject,
input,
TemplateRef,
signal,
ViewContainerRef,
} from '@angular/core';
/**
* A container directive controls the visibility of its content.
*/
@Directive()
export class DeferredContentAware {
contentVisible = signal(false);
readonly preserveContent = input(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[cdkAccordionContent]',
* hostDirectives: [DeferredContent],
* })
* class CdkAccordionContent {}
* ```
*/
@Directive()
export class DeferredContent {
private readonly _deferredContentAware = inject(DeferredContentAware);
private readonly _templateRef = inject(TemplateRef);
private readonly _viewContainerRef = inject(ViewContainerRef);
private _isRendered = false;
constructor() {
effect(() => {
if (
this._deferredContentAware.preserveContent() ||
this._deferredContentAware.contentVisible()
) {
if (this._isRendered) return;
this._viewContainerRef.clear();
this._viewContainerRef.createEmbeddedView(this._templateRef);
this._isRendered = true;
} else {
this._viewContainerRef.clear();
this._isRendered = false;
}
});
}
}