how to send data from selected option to component

Viewed 662

I have json with the following format.

When I select an option, I would like to pass the values (code & description values from json) to the component.

nameList= [
  {
    "code": "1",
    "description": "abc"
  },
  {
    "code": "123",
    "description": "def"
  },
  {
    "code": "100",
    "description": "ijk"
  }
]

HTML

<select [(ngModel)]="description" #category="ngModel" aria-required
 (change)="getNameList()"> //want to send data.code value to component
    <option style="display:none"></option>
    <option *ngFor="let data of nameList"> {{data.description}} 
    </option>
</select>

Demo

2 Answers

You should use [ngValue]="data"

 <option *ngFor="let data of nameList" [ngValue]="data"> {{data.description}} 
 </option>

and access in the component as,

  getNameList() {
     console.log(this.description);
  }

WORKING STACKBLITZ DEMO

You should try to use interface to improve your typescript code Your html could be like this

<hello name="{{exampleSelected?.description}}"></hello>

<select [(ngModel)]="exampleSelected" aria-required (change)="getNameList()">
    <option style="display:none"></option>
    <option *ngFor="let data of nameList" [ngValue]="data"> {{data.description}} 
 </option>
</select>

And your ts should be like this:

import { Component } from '@angular/core';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  exampleSelected;

  nameList = [
    {
      "code": "1",
      "description": "abc"
    },
    {
      "code": "1",
      "description": "def"
    },
    {
      "code": "1",
      "description": "ijk"
    }
  ]

  getNameList() {
    console.log(this.exampleSelected);
  }
}
Related