在angular2的下拉列表中显示json数据

时间:2017-05-25 10:05:33

标签: json angular angular2-forms

这是json网址:https://jsonplaceholder.typicode.com/todos

这是json结构:

{
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },

我希望在下拉列表中显示所有title,请指导。

3 个答案:

答案 0 :(得分:4)

@Component({
  selector: 'my-app',
  template: `
    <select>
      <option  *ngFor="let item of items" [value]="item.title">{{item.title}}</option>
    </select>
  `,
})

export class App {
  items : any;
  constructor(private http:Http) {
    this.http.get('https://jsonplaceholder.typicode.com/todos')
      .subscribe(res => this.items = res.json());
  }
}

工作plunkr

答案 1 :(得分:2)

查看我使用光滑的材料设计样式和一些简单的错误处理创建的工作Plunker

{{Here}}

enter image description here

在您的组件中

执行以下操作:

import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx'

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html',
  styles: [`
  div {
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: start;
    margin-top: 1rem;
  }
  `]
})
export class AppComponent {
  constructor(private http:Http) {
    this.http.get('https://jsonplaceholder.typicode.com/todos')
      .subscribe(res => this.items = res.json(),
    err => console.error('Error: ' + err),
    () => console.log('Voila! you got your list!'));
  }
}

然后在你的模板中添加:

<md-toolbar color="primary">
<h4>Show json data in a dropdown in angular2 - Hamed</h4>
</md-toolbar>

<div> 
<button md-button [mdMenuTriggerFor]="menu">data dropdown menu</button>
<md-menu #menu="mdMenu">
  <button md-menu-item *ngFor="let item of items" [value]="item?.title">{{item?.title}}</button>
</md-menu>
  </div>

答案 2 :(得分:0)

    let todos = "the json data " // make a http call to subscribe to the data

    <select [ngModel]="selectedtitle" (ngModelChange)="onChange($event)" name="select">
        <option [value]="i" *ngFor="let i.title of todos">{{i}}</option>
    </select>