Enhance select component to register options on initialization and remove debug log

This commit is contained in:
Lorenz Hilpert
2024-11-27 11:52:02 +01:00
parent 98a9346c1a
commit 9ba05253e9
2 changed files with 20 additions and 2 deletions

View File

@@ -46,7 +46,7 @@ export class SelectOptionComponent<T = any> implements FocusableOption {
select(event: Event): void {
event.preventDefault();
event.stopPropagation();
console.log('SelectOptionComponent.select', this.value, this._onSelect);
this._onSelect(this.value);
}
}

View File

@@ -13,6 +13,9 @@ import {
ElementRef,
HostBinding,
OnDestroy,
AfterContentInit,
inject,
DestroyRef,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { SelectOptionComponent } from './select-option.component';
@@ -20,6 +23,7 @@ import { IconComponent } from '@shared/components/icon';
import { BaseFormControlDirective } from '@shared/components/form-control';
import { Subject } from 'rxjs';
import { NgIf } from '@angular/common';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'shared-select',
@@ -32,7 +36,9 @@ import { NgIf } from '@angular/common';
imports: [IconComponent, NgIf],
providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: SelectComponent, multi: true }],
})
export class SelectComponent<T = any> extends BaseFormControlDirective implements ControlValueAccessor, OnDestroy {
export class SelectComponent<T = any> extends BaseFormControlDirective implements AfterContentInit, ControlValueAccessor, OnDestroy {
private destroyRef = inject(DestroyRef);
@ContentChildren(SelectOptionComponent)
options: QueryList<SelectOptionComponent>;
@@ -99,6 +105,18 @@ export class SelectComponent<T = any> extends BaseFormControlDirective implement
super();
}
ngAfterContentInit(): void {
this.options.changes.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.options.forEach((option) => {
option.registerOnSelect((value) => this.setValue(value));
});
});
this.options.forEach((option) => {
option.registerOnSelect((value) => this.setValue(value));
});
}
ngOnDestroy() {
this._onDestroy$.next();
this._onDestroy$.complete();