简体   繁体   English

如何使用REST API将JSON值链接到Angular2中的下拉字段?

[英]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. 我正在Web应用程序的前端工作,并且想在我单击HTML页面上的下拉值时接收JSON对象数据。

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. 如果希望将对象json保存为选择元素的模型值,则可以通过在option元素上使用ngValue来使用它。

<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. 如果要在选择值时对值做某事,可以侦听ngModelChange事件。

<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 . 一个有效的例子可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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