gpt4 book ai didi

angular - 使用 *ngFor 范围之外的 *ngFor 数据

转载 作者:行者123 更新时间:2023-12-02 13:19:50 26 4
gpt4 key购买 nike

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

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

最佳答案

<小时/>

除非将其中一项设置为变量,否则无法直接显示 *ngFor 之外的一项。通常这将基于某些事件(例如 click()、mouseover() 等)

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

这是一个正在工作的笨蛋: 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 {}

关于angular - 使用 *ngFor 范围之外的 *ngFor 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com