2017-05-30 39 views
1

我有一个数组,其中4个项目和仪表板上的4个按钮。我想为button1指定item1,用button2指定item2等等。现在,它为每个“英雄”显示4个按钮,总共16个按钮。我试过{{hero.name[2]}}和类似的东西,但只是抓住字母,而不是实际的数组项目。我将不胜感激任何帮助。角度显示按钮中的正确数组项目

dashboard.component.html

<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> 

dashboard.component.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(); 
    } 
} 

hero.service.ts

import { Injectable } from '@angular/core'; 
import { Headers, Http, Response } from '@angular/http'; 
import { Hero } from './hero.class'; 
import { Observable } from "rxjs/Rx"; 

@Injectable() 
export class HeroService { 

    private headers = new Headers({'Content-Type': 'application/json'}); 
    private heroesUrl = 'api/heroes'; // URL to web api 

    constructor(private http: Http){ } 

    getHeroes(): Observable<Hero[]> { 
    return this.http.get(this.heroesUrl) 
       .map(response => response.json().data as Hero[]); 
    } 

    getHero(id: number): Observable<Hero> { 
    const url = `${this.heroesUrl}/${id}`; 
    return this.http.get(url) 
     .map(response => response.json().data as Hero); 
    } 
} 

回答

2

您可以使用内置的index属性*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

+0

几乎工作,唯一的问题是1第1项和第2项的回报ID当单击该按钮,4号也返回3 – John

+0

@约翰指数的ID从0开始,这样你就可以增加它由1 :-) – echonax

+2

这应该是显而易见的,感谢您的帮助,效果很好。 – John