简体   繁体   中英

How do I link JSON values to a drop-down field in Angular2 using REST API?

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.

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 .

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