点击路由器插座Angular2中的* ngFor项目

时间:2017-01-17 21:22:17

标签: json angular routing router-outlet

我有一个*ngFor生成的列表,其中每个项目都来自json

我想要的是在隐藏其他项目的同时获取router-outlet视图中的点击项目。

将其视为产品列表和产品卡。当您单击特定项目时,您重定向到该项目产品的整页。所以,我需要相同的方法。

现在点击即可获得所需的网址。所以我不需要为router-outlet视图设置一个特殊的URL,只需在那里渲染点击的项目。

我的*ngFor结构:

<div class="releases-component">
    <div class="release" 
    *ngFor="let release of releases"
    (click)="routerDisplay($event)">

        <img src="{{release.image}}" 
        alt="Release image" 
        [routerLink]="['/releases', release.id ]">

        <h3 class="release--name" 
        [routerLink]="['/releases', release.id ]">{{release.name}}</h3>

        <span class="release--year" 
        [routerLink]="['/releases', release.id ]">{{release.year}}</span>
    </div>

    <div class="release--view">
        <router-outlet>{{ The Clicked Item! }}</router-outlet>
    </div>
</div>

我的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()
export class ReleasesService {

    constructor(private http: Http) {

    }


    getReleases() {
        return this.http.request('./allReleases.json')
        .map(res => res.json());
    }

    getData(res: Response){

    }

    getReleaseInfo(){

    }
}

我的json

[
    {
      "id":"release-1",
      "name": "Release1 name",
      "image": "./cover1.jpg",
      "year": "2014"
    },
    {
      "id":"release-2",
      "name": "Release2 name",
      "image": "./release2.jpg",
      "year": "2015"
    }
]

我的路线:

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'releases', component: ReleasesComponent },
  { path: 'releases/:id', component: ReleasesComponent },
  { path: 'distro', component: DistroComponent },
  { path: 'contacts', component: ContactsComponent }
];

1 个答案:

答案 0 :(得分:1)

        <div class="releases-component">
            <div class="release" 
            *ngFor="let release of releases"
            (click)="routerDisplay($event),onSelect(release)">

                <img src="{{release.image}}" 
                alt="Release image" 
                [routerLink]="['/releases', release.id ]">

                <h3 class="release--name" 
                [routerLink]="['/releases', release.id ]">{{release.name}}</h3>

                <span class="release--year" 
                [routerLink]="['/releases', release.id ]">{{release.year}}</span>
            </div>

            <div class="release--view" *ngIf="selectedRelease">
             <label>id: {{selectedRelease.id}}</label><br/>
             <label>name: {{selectedRelease.id}}</label><br/>
             <label>year : {{selectedRelease.year}}</label><br/>
            </div>
        </div>

In you controller:
onSelect(release){
this.selectedRelease=release;
    }