提问人:Bryant Irawan 提问时间:8/22/2022 最后编辑:Bryant Irawan 更新时间:8/23/2022 访问量:218
在 angular *ngFor 循环中使用 $(this)
Using $(this) in angular *ngFor loop
问:
我正在尝试创建一个图像模式,如果您单击图像,它会创建一个放大的预览。我有三张来自服务的图像,我使用 *ngFor 显示所有三张图像。但是,当单击一张图像时,所有三张图像都会放大。我知道我可以使用$(this),因此点击函数知道要放大哪个图像网址,但我不确定如何实现。任何帮助将不胜感激。如果我需要安装jquery才能使其工作或导入它,请告诉我。谢谢!
元件
import { Component, OnInit } from '@angular/core';
import { RandomdogpicsService } from './randomdogpics.service';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {
picData: any;
title:string = 'Random dog pics';
showModal: boolean = false;
show()
{
this.showModal = true; // Show-Hide Modal Check
}
//Bootstrap Modal Close event
hide()
{
this.showModal = false;
}
constructor(private threeRandomData: RandomdogpicsService){}
ngOnInit()
{
this.threeRandomData.getThreeRandom().subscribe((result) => {
this.picData = result
})
}
}
[HTML全文]
<h1>{{title}}</h1>
<ul *ngFor="let randomURL of picData.message">
<li >
<a href="#" (click) = "show()">
<img id="imageresource" src="{{randomURL}}" style="width: 125px; height: 125px;">
</a>
<!--Creates the bootstrap modal where the image will appear -->
</li>
</ul>
<div [style.display]="showModal ? 'block' : 'none'" class="modal" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Image preview</h4>
</div>
<div class="modal-body">
<!-- need to pass {{randomURL}} here -->
<img src="" id="imagepreview" style="width: 425px; height: 425px;" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" (click) = "hide()">Close</button>
</div>
</div>
</div>
</div>
更新:按照这个建议,我将模态 div 移到了 for 循环之外。我修改了我的 CSS 来阻止屏幕,这样我就可以将其保留在 for 循环中,并且用户不会注意到所有图像都已显示。但是,显示的图像始终是 for 循环的最后一个图像。因此,我要么 1) 将 div 模态放在 for 循环中,但弄清楚如何防止它在 for 循环中选择最后一个 url,或者 2) 我将 div 模态放在 for 循环之外,但将 {{randomULR}} 传递给 img src。
答:
5赞
Zerotwelve
8/22/2022
#1
你(几乎)永远不应该在 Angular 中使用 jQuery。Angular 基本上可以做 jQuery 所做的一切。
在您的例子中,您可以将单击的图像作为参数函数传递: 这样您就知道点击了 URL。
您必须将模态放在 ngFor 之外,否则您将有 3 个模态。(click)="show(randomURL)"
我可以给你的一个提示是,使用 Angular Material Dialog 或 CDK Dialog 来显示一个模态而不是你自己的模态。
评论
0赞
Bryant Irawan
8/23/2022
谢谢是有道理的。我应该如何更改组件中的show()以接受该randomurl参数?我收到一个错误,说我放置的任何参数都有一个隐式的任何错误,即使在将其键入为字符串脚本后也是如此。
0赞
Bryant Irawan
8/23/2022
另外,是的,我将研究 Angular Material Dialog 或 CDK。谢谢
0赞
Zerotwelve
8/23/2022
show(randomURL: string){ }
这看起来是一个非常基本的问题。我的建议是遵循整个教程(所有 6 个部分)。这很有帮助!!angular.io/tutorial
0赞
Bryant Irawan
8/24/2022
你可能应该这样做,但我只是使用材料对话弄清楚了,这似乎是一种更好的方法。
1赞
Zerotwelve
8/24/2022
好。如果您觉得我的答案解决了您的问题,请考虑将其标记为已接受
评论