How to get full item property from dropdown formControl valueChanges?

Discussão em 'Angular' iniciado por aii-yin, Dezembro 20, 2024.

  1. aii-yin

    aii-yin Guest

    What i want is some guidance/suggestion on usage of the formControl.valueChanges. When an item is selected from a drop-down box, i want to be able to access the full item of the selected item, and not just the itemID, when using the valueChanges

    my current scenario are like so:

    // component.ts
    interface SomeItem {
    id: number;
    name: string;
    }

    someIDFormControl = new FormControl(0)
    someData$: Observable<SomeItem[]> = this._someService.getAll()

    selectedItem$ = this.someIDFormControl.valueChanges.pipe(
    map(itemID => {
    // how can i get the full item property from here
    })
    )


    <select [formControl]="someIDFormControl">
    <option *ngFor="let item of (someData$|async)" [value]="item.id">{{ item.name }}</option>
    </select>


    with following requirements:

    • must use FormControl.valueChanges because I intend to use the {emitEvent: false} with patchValue/setValue

    Simply based on what I currently know, the only idea i got is to pipe the someData$ with shareReplay(), then combine with switchMap\map pipe. But this would require additionally find again from the array which doesn't seems ideal(?).

    example:

    someData$: Observable<SomeItem[]> = this._someService.getAll().pipe(shareReplay(1))
    selectedItem$ = this.someIDFormControl.valueChanges.pipe(
    switchMap(id => {
    return this.someData$.pipe(map(itemArr => itemArr.find(item => item.id === id)))
    })
    )

    Continue reading...

Compartilhe esta Página