Skip to content

Commit 4bb1655

Browse files
committed
feat: add generic list directive
1 parent e955435 commit 4bb1655

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { ListDirective } from './list.directive';
2+
3+
describe('ListDirective', () => {
4+
it('should create an instance', () => {
5+
const directive = new ListDirective();
6+
expect(directive).toBeTruthy();
7+
});
8+
});
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import {
2+
Directive,
3+
inject,
4+
Input,
5+
TemplateRef,
6+
ViewContainerRef,
7+
} from '@angular/core';
8+
9+
interface ListStudentTemplateContext<Ctx> {
10+
$implicit: Ctx;
11+
appList: Ctx;
12+
index: number;
13+
}
14+
15+
@Directive({
16+
selector: 'ng-template[listTemplateDirective]',
17+
})
18+
export class ListDirective<Ctx> {
19+
private readonly tpl =
20+
inject<TemplateRef<ListStudentTemplateContext<Ctx>>>(TemplateRef);
21+
22+
private readonly vcr = inject(ViewContainerRef);
23+
24+
@Input() set listOf(list: Ctx[] | readonly Ctx[] | null | undefined) {
25+
const arr = (list ?? []) as Ctx[];
26+
this.vcr.clear();
27+
arr.forEach((item, index) => {
28+
this.vcr.createEmbeddedView(this.tpl, {
29+
$implicit: item,
30+
appList: item,
31+
index,
32+
});
33+
});
34+
}
35+
36+
static ngTemplateContextGuard<Ctx>(
37+
_dir: ListDirective<Ctx>,
38+
ctx: unknown,
39+
): ctx is ListStudentTemplateContext<Ctx> {
40+
return true;
41+
}
42+
}

0 commit comments

Comments
 (0)