1
1
import {
2
- AfterContentInit ,
3
2
booleanAttribute ,
4
3
Component ,
5
- ContentChildren ,
4
+ computed ,
5
+ contentChildren ,
6
+ inject ,
6
7
Input ,
7
8
OnDestroy ,
8
9
OnInit ,
9
- QueryList
10
+ TemplateRef
10
11
} from '@angular/core' ;
11
12
import { NgTemplateOutlet } from '@angular/common' ;
12
13
@@ -26,15 +27,15 @@ let nextId = 0;
26
27
imports : [ AccordionButtonDirective , NgTemplateOutlet , CollapseDirective ] ,
27
28
host : { class : 'accordion-item' }
28
29
} )
29
- export class AccordionItemComponent implements OnInit , OnDestroy , AfterContentInit {
30
- constructor ( private accordionService : AccordionService ) { }
30
+ export class AccordionItemComponent implements OnInit , OnDestroy {
31
+ readonly # accordionService = inject ( AccordionService ) ;
31
32
32
33
/**
33
34
* Toggle an accordion item programmatically
34
35
* @type boolean
35
36
* @default false
36
37
*/
37
- @Input ( { transform : booleanAttribute } ) visible : string | boolean = false ;
38
+ @Input ( { transform : booleanAttribute } ) visible : boolean = false ;
38
39
39
40
@Input ( )
40
41
set open ( value : boolean ) {
@@ -47,25 +48,32 @@ export class AccordionItemComponent implements OnInit, OnDestroy, AfterContentIn
47
48
}
48
49
49
50
contentId = `accordion-item-${ nextId ++ } ` ;
50
- itemContext = { $implicit : < boolean > this . visible } ;
51
- templates : any = { } ;
52
- @ContentChildren ( TemplateIdDirective , { descendants : true } ) contentTemplates ! : QueryList < TemplateIdDirective > ;
51
+
52
+ get itemContext ( ) {
53
+ return { $implicit : < boolean > this . visible } ;
54
+ }
55
+
56
+ readonly contentTemplates = contentChildren ( TemplateIdDirective , { descendants : true } ) ;
57
+
58
+ readonly templates = computed ( ( ) => {
59
+ return this . contentTemplates ( ) . reduce (
60
+ ( acc , child ) => {
61
+ acc [ child . id ] = child . templateRef ;
62
+ return acc ;
63
+ } ,
64
+ { } as Record < string , TemplateRef < any > >
65
+ ) ;
66
+ } ) ;
53
67
54
68
ngOnInit ( ) : void {
55
- this . accordionService . addItem ( this ) ;
69
+ this . # accordionService. addItem ( this ) ;
56
70
}
57
71
58
72
ngOnDestroy ( ) : void {
59
- this . accordionService . removeItem ( this ) ;
73
+ this . # accordionService. removeItem ( this ) ;
60
74
}
61
75
62
76
toggleItem ( ) : void {
63
- this . accordionService . toggleItem ( this ) ;
64
- }
65
-
66
- ngAfterContentInit ( ) : void {
67
- this . contentTemplates . forEach ( ( child : TemplateIdDirective ) => {
68
- this . templates [ child . id ] = child . templateRef ;
69
- } ) ;
77
+ this . #accordionService. toggleItem ( this ) ;
70
78
}
71
79
}
0 commit comments