【问题标题】:Use data from *ngFor outside of *ngFor scope在 *ngFor 范围之外使用来自 *ngFor 的数据
【发布时间】:2017-12-11 04:31:16
【问题描述】:

这是一个我想实际解决的示例问题。您的帮助将不胜感激。非常感谢!

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

【问题讨论】:

  • 您想要预览每个项目还是特定项目?
  • @ThinkingMedia 我想要预览 *ngFor 范围之外的特定项目。我实际上使用的是轮播。

标签: angular ngfor


【解决方案1】:

除非您将其中一项设置为变量,否则无法直接在 *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 {}

【讨论】:

    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2021-08-18
    • 2021-01-04
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多