简体   繁体   中英

How to select multitple value of object when click on button in Angular selection option dropdown menu

I am placing JSON result in option list of selection dropdown menu

[
{
    "id": "1596700684533_",
    "name": "Usman Abbas Ghulam Abbas",
    "fcm": "344"
},
{
    "id": "1596700972722_",
    "name": "Muhammad Ali",
    "fcm": "0"
},
{
    "id": "1596702420255_",
    "name": "Abdul Hannan Abdul Mannan",
    "fcm": "234"
}
]
  • how can i select full object and values of object like id and fcm both when click on button

my component.htlm code is

<select (change)="Selected($event)">
              <option *ngFor="let group of groups" [value]="group.fcm">
                {{group.name}}
              </option>
            </select>

currently on button click i can get either one value id or fcm

Selected(event: any){
//update the ui
this.selectedName = event.target.value;
//this.selectedId = event.targent.value.id
this.hide=false;



}


getVal(){
  this.button=this.selectedName;
  console.log("hre is selected values for option " + this.selectedName);
 

  }

You can simply set the value of the option to be the id . In your (change) event emitter handler, find the Item with that id

See Below code Link to stackblitz demo

<select (change)="Selected($event)">
  <option *ngFor="let group of groups" [value]="group.id">
    {{group.name}}
  </option>
</select>

Typescript file

  Selected($event) {
    const selectedObject = this.groups.find(({id}) => id === event.target['value'])
    this.selectedName = selectedObject.name
    this.selectedId = selectedObject.id
  }

1st Way(set group instead of group.fcm)

<option *ngFor="let group of groups" [value]="group">

2nd Way(Get the fcm / id and filter the existing record on top it)

<option *ngFor="let group of groups" [value]="group.id">

Component

 Selected(event: any){
  this.selectedObj= data.filter(item => item.id = event.target.value)
  this.hide=false;
}

I think 2nd way will give you much more control over your data set and ui visibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM