【问题标题】:How to get .json objects by id in Angular 2?如何在 Angular 2 中通过 id 获取 .json 对象?
【发布时间】:2019-01-28 17:34:18
【问题描述】:

从我的下拉列表中选择一个项目后,我试图通过 id 从 JSON 文件中获取对象。到目前为止,我已经设法从 JSON 中检索所有对象,但不是通过 ID。

打字稿

showInfo() {
    var selected = this.diadikasies.filter(x=> x.content);
    console.log (selected);
}

HTML

<div *ngIf="diadikasies && diadikasies.length > 0" class="form-group">
    <label for="diadikasies">
        <i class="fas fa-clipboard-list" aria-hidden="true"></i> Please Select: </label>
    <select #proc (change)="showInfo()">
        <option [ngValue]="undefined" disabled selected>Επιλέξτε Διαδικασία</option>
        <option *ngFor="let diad of diadikasies" [value]="diad.id">{{ diad.title.rendered }}</option>
    </select>
</div>

提前致谢。

【问题讨论】:

    标签: html angular typescript filter


    【解决方案1】:

    可以同时使用 ngModel 和 ngModelChange 来获取选中的值

    <select #proc [(ngModel)]="selectedObj" (ngModelChange)="showInfo()">
    

    在 showInfo 方法内部,

     var selected = this.diadikasies.filter(x=> x.id == this.selectedObj.id);
    

    【讨论】:

    • 不应该是x.id === this.selectedObj.id in filter吗?
    【解决方案2】:

    您可以使用find() 方法,如下所示

    TS 文件

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      description;
    
      opts = [{
        id: 1,
        name: 'Test 1',
        description: 'This is Test 1 description'
      }, {
        id: 2,
        name: 'Test 2',
        description: 'This is Test 2 description'
      }];
    
      showInfo(value) {
        let selectedOpt = this.opts.find(opt => opt.id == value);
        this.description = selectedOpt.description;
      }
    }
    

    在模板文件中

    <div *ngIf="opts && opts.length > 0" class="form-group">
        <label for="opts">
            <i class="fas fa-clipboard-list" aria-hidden="true"></i> Please Select: </label>
        <select #proc (change)="showInfo(proc.value)">
            <option [ngValue]="undefined" disabled selected>Επιλέξτε Διαδικασία</option>
            <option *ngFor="let diad of opts" [value]="diad.id">{{ diad.name }}</option>
        </select>
    </div>
    <div>{{ description }}</div>
    

    您可以从这里找到工作示例Stackblitz

    【讨论】:

    • 非常感谢。确实很简单,尽管我没有想到 find()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2018-04-02
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多