没有办法直接显示的* 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 {}
你想每个项目或特定项目的预览? – cgTag
@ThinkingMedia我想要预览* ngFor范围外的特定项目。我实际上使用旋转木马。 –