在 *ngFor 循环外部使用 *ngFor 中的数据范围

4

这里有一个样例问题需要解决。非常感谢你的帮助。谢谢!

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

您想要每个项目的预览还是特定项目的预览? - Reactgular
@ThinkingMedia 我想在 *ngFor 范围之外预览特定项目。我实际上正在使用一个轮播图。 - Lex Caraig
1个回答

2

如果不将其中一项设置为变量,通常情况下无法直接在 *ngFor 之外显示单个项目。这通常是基于某些事件(例如 click()、mouseover() 等)触发的。

以下是一个示例,展示了一个常见模式:用户点击您的图像后,这将设置另一个变量,然后在组件的任何其他位置根据需要显示该变量。

以下是一个工作的 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 {}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接