2017-07-07 60 views
1

以下是我想要實際解決的示例問題。你的幫助將非常感激。非常感謝!使用來自* ngFor以外的數據* ngFor範圍

<div> 
    <div> 
    <!-- is it possible to put the item.preview here? 
     It is outside of *ngFor 
    --> 
    </div> 
    <div *ngFor="let item of items"> 
     <img [src]="item.cover" alt="item.name"> 
    </div> 
</div> 
+0

你想每個項目或特定項目的預覽? – cgTag

+0

@ThinkingMedia我想要預覽* ngFor範圍外的特定項目。我實際上使用旋轉木馬。 –

回答

1

沒有辦法直接顯示的* ngFor之外的一個項目,除非你設置的項目到變量之一。通常這將基於某些事件(例如點擊(),鼠標懸停()等)。

下面是一個示例,顯示了用戶單擊圖像時的常見模式,這設置了另一個變量,然後顯示在任何地方根據需要在組件上進行其他操作

這裏是一個工作plunker: https://plnkr.co/edit/TzBjhisaPCD2pznb10B0?p=preview

import {Component, NgModule, VERSION, OnInit, Input} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

interface Item { 
    id: number; 
    name: string; 
    covor: string 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
    </div> 
    <div> 
    <div> 
     {{selectedItem | json}} 
    </div> 
    <div *ngFor="let item of items"> 
     <img [src]="item.cover" alt="item.name" (click)="selectItem(item)"> 
    </div> 
    </div> 
    `, 
}) 
export class App implements OnInit { 
    name:string; 

    // This is an input just to show that this might be where the data comes from 
    // otherwise call a service to set the data initially 
    @Input() items: Item[] = [ 
    {id: 1, name: 'test', cover: 'https://i.vimeocdn.com/portrait/58832_300x300'}, 
    {id: 2, name: 'test2', cover: 'https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300'}, 
    ]; 
    selectedItem: Item; 

    constructor() { 
    this.name = `Angular! v${VERSION.full}` 
    } 

    ngOnInit() { 
    // you can init your item here 
    if(this.items.length > 0) { 
     this.selectedItem = this.items[0]; 
    } 
    } 

    selectItem(item: Item) { 
    this.selectedItem = item; 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {}