首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用*ngFor作用域以外的*ngFor数据

使用*ngFor作用域以外的*ngFor数据
EN

Stack Overflow用户
提问于 2017-07-07 01:33:28
回答 1查看 2.1K关注 0票数 4

下面是我想要解决的一个示例问题。你的帮助会很感激的。非常感谢!

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2017-07-07 04:19:51

没有一种方法可以直接显示*ngFor之外的一项,除非您将其中一项设置为变量。通常,这将基于某些事件(e.x )。单击()、mouseover()等.)

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

下面是一个工作柱塞:https://plnkr.co/edit/TzBjhisaPCD2pznb10B0?p=preview

代码语言:javascript
复制
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 {}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44961229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档