-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-children.directive.ts
48 lines (41 loc) · 1.4 KB
/
check-children.directive.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
import {
Directive,
QueryList,
ContentChildren,
ContentChild,
AfterContentInit
} from '@angular/core';
import { NgControl, AbstractControl } from '@angular/forms';
import { merge } from 'rxjs';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { SelectGroupDirective } from './select-group.directive';
import { debounceTime } from 'rxjs/operators';
@UntilDestroy()
@Directive({
selector: '[checkChildren]'
})
export class CheckChildrenDirective implements AfterContentInit {
@ContentChildren(NgControl, { descendants: true })
controls!: QueryList<NgControl>;
@ContentChild(SelectGroupDirective)
selectGroup!: SelectGroupDirective;
ngAfterContentInit(): void {
this.selectGroup.checkChanges$
.pipe(untilDestroyed(this))
.subscribe((checked) => {
this.controls.forEach(({ control }) => control?.patchValue(checked));
});
const changes = this.controls.map(
({ control }) => (control as AbstractControl).valueChanges
);
merge(...changes)
.pipe(untilDestroyed(this), debounceTime(0))
.subscribe(() => {
const controls = this.controls.toArray();
const every = controls.every(({ control }) => control?.value);
const some = controls.some(({ control }) => control?.value);
this.selectGroup.checked = every;
this.selectGroup.indeterminate = !every && every !== some;
});
}
}