Here is a sample problem that i want to actually solve. Your help will really appreciate. Thanks a lot!
<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>
There is not a way to directly show one item outside of an *ngFor unless you set one of the items into a variable. Usually this would be based on some event (e.x. click(), mouseover(), etc..)
Here is an example showing a common pattern where a user clicks your image, this sets another variable which is then displayed anywhere else on the component as needed.
Here is a working 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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With