Angular在按钮中显示正确的数组项

时间:2017-05-30 16:31:50

标签: arrays angular typescript

我有一个包含4个项目的数组,以及仪表板上的4个按钮。我想用button1分配item1,用button2等分配item2。现在它为每个“hero”显示4个按钮,总共16个按钮。我尝试了Iterable[User]和类似的东西,但只是抓取字母而不是实际的数组项。我将不胜感激任何帮助。

dashboard.component.html

{{hero.name[2]}}

dashboard.component.ts

<h3>Calibrations</h3>
<div class="grid grid-pad">
   <a *ngFor="let hero of heroes" [routerLink]="['/detail', hero.id]"> 
    <button style ="min-height: 70px" (click)="gotoClick(1)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(2)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(3)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(4)">{{hero.name}}</button>
  </a>
</div>

hero.service.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero.class';
import { HeroService } from '../hero.service';
import { StepService } from '../step.service';
@Component({
  moduleId: module.id,
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService, private _stepService: StepService, private _teststepService: StepService) { }

  ngOnInit() {
    this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes);
  }

  private test: number;
  gotoClick(value: number){
    this._stepService.setTest(value);
    this._teststepService.apiURL();
  }
}

1 个答案:

答案 0 :(得分:2)

您可以使用*ngFor的内置索引属性:

<div class="grid grid-pad">
   <a *ngFor="let hero of heroes; let i = index;" [routerLink]="['/detail', hero.id]"> 
    <button style ="min-height: 70px" (click)="gotoClick(i)">{{hero?.name}</button>
  </a>
</div>

文档:https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html