所以,我有一个由ngFor表生成的。 在每一行中,我都有按钮,图像为背景:
<tbody>
<tr *ngFor='let movie of movies let i = index'>
<td>...some values here...</td>
<td>
<span>
<button name="watchLater_butom">
<img [src]='watchLaterIcon' alt="icon (click)='AddToWatchLater(i)'>
</button>
</span>
</td>
</tbody>
我的组件:
export class MyComponent{
watchLaterIcon: string = '/assets/watchLater_icon.png';
emptyWatchLaterIcon: string = '/assets/emptyWatchLater_icon.png';
AddToWatchLater(i : number) : void {
var tempWatchLaterIcon = this.watchLaterIcon;
this.watchLaterIcon = this.emptyWatchLaterIcon;
this.emptyWatchLaterIcon = tempWatchLaterIcon;
}
}
到目前为止,通过单击任何按钮可以更改所有图像。我需要的是只更改一个图像src以获得我点击的按钮。
我认为必须用AddToWatchLater()
方法完成某些事情。我想,它可能通过我传递给方法的行索引起作用,但不知道它是如何工作的。
答案 0 :(得分:0)
您可以根据每个电影在对象中管理它的数组数据的位置动态更改,这是一个简单的示例:
Ts文件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
watchLaterIcon: string = 'https://www.materialui.co/materialIcons/action/watch_later_black_192x192.png';
emptyWatchLaterIcon: string = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT53nVsfr2bXkVsrEZ8Mjsbwk4-dQzfPL1XuVWNPVy5Ex52AQAM';
movies:{} = [{ name: 'Movie 1' }, { name: 'Movie 2' }]
AddToWatchLater(index){
const actualsrc = this.movies[index].src;
if(actualsrc){
this.movies[index].src = actualsrc === this.watchLaterIcon ? this.emptyWatchLaterIcon : this.watchLaterIcon;
}else {
this.movies[index].src = this.emptyWatchLaterIcon;
}
}
}
Html文件:
<table>
<tbody>
<tr *ngFor='let movie of movies let i = index'>
<td>...some values here...</td>
<td>
<span>
<button name="watchLater_butom">
<img [src]="movie.src ? movie.src : watchLaterIcon" alt="icon" (click)="AddToWatchLater(i)" >
</button>
</span>
</td>
</tr>
</tbody>
</table>
答案 1 :(得分:0)
在.ts文件中,首先创建一个新数组,此数组的每个元素都将具有watchLaterIcon字符串,其长度应与movies数组相同,因此在构造函数中添加for循环:
imageSources: string[] = [];
constructor()
{
for(let i=0; i<this.movies.length; i++)
{
this.imageSources[i] = watchLaterIcon;
}
}
然后为按钮'ButtonComponent'创建一个新组件,并编辑.html文件,以便ngFor迭代按钮组件并将图像源作为输入传递给组件:
<table>
<tbody>
<tr *ngFor='let imageSource of imageSources>
<td>...some values here...</td>
<td>
<span>
<app-button [inputImageSrc]="imageSource"><app-button>
</span>
</td>
</tr>
</tbody>
</table>
按钮组件.HTML文件:
<button (click)="getSelected()">
<img src={{imgSrc}} alt="icon">
</button>
按钮组件.Ts文件:
emptyWatchLaterIcon: string = '/assets/emptyWatchLater_icon.png';
@Input('inputImageSrc') imgSrc: string; // get input and use as 'src' in the img tag
getSelected() // Change the image source, applies only to the clicked button of the ngFor loop.
{
this.imgSrc = emptyWatchLaterIcon;
}