-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert-view-ref.directive.ts
More file actions
56 lines (51 loc) · 1.58 KB
/
insert-view-ref.directive.ts
File metadata and controls
56 lines (51 loc) · 1.58 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
import { Directive, Input, ViewContainerRef, ViewRef, inject } from '@angular/core'
/**
* Directive to insert a viewRef to the template.
* using this directive makes something like `@ViewChild('myContainer', {read: ViewContainerRef}) myContainer:ViewContainerRef` superfluous
* @example
* ```typescript
* class ComponentX {
* readonly componentRef: ComponentRef<any> = createComponent(MyDynamicComponent, {...})
* }
* ```
* ```html
* <ng-template [scInsertViewRef]="componentRef.hostView"></ng-template>
* ```
*/
@Directive({ selector: '[scInsertViewRef]', standalone: true })
export class InsertViewRefDirective {
private readonly container = inject(ViewContainerRef)
@Input()
set scInsertViewRef(val: ViewRef | null | undefined) {
this.container.clear()
if (val) {
this.insert(val)
}
}
get hasAttachedView(): boolean {
return this.container.length > 0
}
/**
* Inserts a view into the container.
* @throws when a view is already attached
*/
insert(val: ViewRef) {
if (this.hasAttachedView) {
throw new Error('container already has a view attached')
}
this.container.insert(val)
}
/**
* Detaches the view from the container and returns its {@link ViewRef}.
* When detaching a view, it will no longer be auto-destroyed when the directive gets destroyed
* therefore it's necessary to manually destroy it manually at some point
* @throws when no view attached
*/
detach(): ViewRef {
const r = this.container.detach(0)
if (!r) {
throw new Error('container has no view attached')
}
return r
}
}