0

I'm working on the front-end side of a web application and would like to receive JSON object data when I click on the drop down values on my HTML page.

Someone please explain to me how this can be done.

K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
Atif T.
  • 9
  • 7
  • 2
    Can you provide some code? Have you already tried something ? – JiiB Feb 02 '18 at 20:49
  • do you want to have a json object in the ngModel? you can use ngValue for that. – toskv Feb 02 '18 at 20:53
  • Possible duplicate of [Angular 2 - fetch data from local json to populate dropdown](https://stackoverflow.com/questions/42969843/angular-2-fetch-data-from-local-json-to-populate-dropdown) – Jako Feb 02 '18 at 21:30
  • To be clear, there's no such thing as a "json object" There's an object, and there's a string in JSON format. – Heretic Monkey Feb 03 '18 at 00:59

1 Answers1

0

If you wish to have an object json saved as a select element's model value you can use it by using ngValue on the option elements.

<select [(ngModel)]="selected">
         <option *ngFor="let value of values" [ngValue]="value">{{value.name}}</option>
      </select>|

You can see a working example here.

If you want to do something with the value when a value is selected you can listen on the ngModelChange event.

<select [(ngModel)]="selected" (ngModelChange)="handleChange($event)">
         <option *ngFor="let value of values" [ngValue]="value">{{value.name}}</option>
      </select>|

And define the method to call in your controller.

export class App {
  name:string;
  selected = null;
  values = [{name:'a'}, {name:'b'}, {name:'c'}]
  history = [];
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  handleChange(value) {
    this.history.push(value);
  }
}

A working example can be found here.

toskv
  • 30,680
  • 7
  • 72
  • 74