Home > Mobile >  Displaying objects dropdown from an array - Angular
Displaying objects dropdown from an array - Angular

Time:01-24

I need help with this implementation. Im have an array loaded with some objects, and i want to display only the property called "name" of those objects in the dropdown, and when i select one of those options, i want to have access to the entire object. Is that possible?

At the moment i tried this code:

HTML of the component:

<select (change)="update($event)">
    <option value="default">----</option>
    <option value={{item}} *ngFor="let item of noMensuales">
        {{item.nombre}}
    </option>
</select>

TS of the component:

import { Component, OnInit } from '@angular/core';
import { ServicesDebCredService } from 'src/app/services/services-deb-cred.service';

@Component({
  selector: 'app-pago-no-mensual',
  templateUrl: './pago-no-mensual.component.html',
  styleUrls: ['./pago-no-mensual.component.css']
})
export class PagoNoMensualComponent implements OnInit {
  noMensuales: any = []
  seleccionado:any = {}

  constructor(private _serviceDebCred: ServicesDebCredService) { }

  update(e : any) {
    this.seleccionado = e.target.value
    console.log(this.seleccionado)
    console.log(this.seleccionado.nombre)
  }

  ngOnInit(): void {
    this.getNoMensuales()
  }

  getNoMensuales() {
    this._serviceDebCred.getNoMensuales().subscribe((res) => {
      this.noMensuales = res.noMensuales
    })
  }

}

The thing is that, on the "seleccionado" field (the one i want to select and get the entire object) i have an empty object when i click on one of the list...

CodePudding user response:

Yes it is possible, you need to tweak your code little bit, If you have an ID in your object just refer that pass that ID as value.

HTML file

<select (change)="update($event)">
    <option value="default">----</option>
    <option value={{item.id}} *ngFor="let item of noMensuales">
        {{item.nombre}}
    </option>
</select>

TS file: Into your update function:

update(e : any) {
    let selectedObject = {};
    this.noMensuales.map((res)=>{
     if(e.target.value == res.id){
       selectedObject = res;
     }
    });
    console.log(selectedObject)
  }

If you dont have ID or unique values in your object you can do it with ngFor index as well

CodePudding user response:

You can easily access the object by referring this.

<select (change)="update($event)">

<option value="default">----</option>

<option value={{item}} *ngFor="let item of noMensuales">
    {{item.nombre}}
</option>

I have reduced your update function code line for get your response very quickly

update(e : any) {

console.log(this.noMensuales.filter(item => item.id === e.target.value)[0])

}

  • Related