Angular 2数组按id提取特定数据

时间:2016-06-17 12:15:02

标签: angular

如何使用id从数组中提取特定数据并在div中使用它。

home.component.ts文件

import { Component } from '@angular/core';
import { HomeProjectComponent } from './home-project.component';
import { NewsletterComponent } from './../shared/newsletter/newsletter.component';

export class Project {
  id: number;
  name: string;
  title: string;
  status: string;
}

const PROJECTS: Project[] = [
  { id: 1,
    name: 'name1',
    title: 'title1',
    status: 'status1'
  },
  { id: 2,
    name: 'name2',
    title: 'title2',
    status: 'status2'
  },
  { id: 3,
    name: 'name3',
    title: 'title3',
    status: 'status3'
  },
....
{ id: 100,
    name: 'name100',
    title: 'title100',
    status: 'status100'
  },
];


@Component({
  selector: 'home',
  templateUrl: './app/home/home.component.html',
  styleUrls: ['./app/home/home.component.css'],
  directives: [HomeProjectComponent, NewsletterComponent]
})

export class HomeComponent {
  projects = PROJECTS;
}

这是我的html代码,我试图获取带ID的项目的名称,标题和状态 home.component.html

{{project.name}},{{project.title}}和{{project.status}}必须相同

get data with id 20
<home>
  <h1>{{project.name}}</h1>
  <h2>{{project.title}}</h2>
  <p>{{project.status}}</p>
</home>

// SOME HTML

get data with id 64
<home>
  <h1>{{project.name}}</h1>
  <h2>{{project.title}}</h2>
  <p>{{project.status}}</p>
</home>

// SOME HTML

get data with id 69
<home>
  <h1>{{project.name}}</h1>
  <h2>{{project.title}}</h2>
  <p>{{project.status}}</p>
</home>

2 个答案:

答案 0 :(得分:1)

@Component({
  selector: 'home',
  templateUrl: './app/home/home.component.html',
  styleUrls: ['./app/home/home.component.css'],
  directives: [HomeProjectComponent, NewsletterComponent]
})

export class HomeComponent {
  projects = PROJECTS;

  projectId2 = this.extractProjectWithId(2);

  extractProjectWithId(id){
      let i;
      for(i = 0; i< this.projects.length; i++)
      {
         if(this.projects[i].id === id)
          return this.projects[i];
      }

      return null;
    }
}
<div *ngIf="projectId2"> // extract data with ID 2 from project 
  <h1>{{projectId2.name}}</h1>
  <h2>{{projectId2.title}}</h2>
  <p>{{projectId2.status}}</p>
</div>

答案 1 :(得分:1)

我会编写一个返回id为2的对象的方法。例如:

getObjectById(id: number) {
  return PROJECTS.filter(x => x.id == id);
}

阅读

<home> // extract data with ID 2 from project 
  <h1>{{ getObjectById(2)[0].name }}</h1>
  <h2>{{ getObjectById(2)[0].title }}</h2>
  <p>{{ getObjectById(2)[0].status }}</p>
</home>

更新新修改

由于您需要数组中的所有project,为什么不使用*ngFor打印它们:

<home *ngFor="let project of PROJECTS"> // extract data with ID 2 from project 
  <h1>{{ project.name }}</h1>
  <h2>{{ project.title }}</h2>
  <p>{{ project.status }}</p>
</home>

这简化了插值{{ }},您不需要任何其他函数来获取特定元素。 如果您关心projects的序列,则创建成员变量

projectInSequence: Project[];

并按所需顺序推送项目,ngFor将更改为*ngFor="let project of projectInSequence。填充projectInSequence可以在生命周期挂钩https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

中完成