在角度 *ngFor 循环中使用 $(this)

Bry*_*wan 0 jquery this ngfor angular

我正在尝试创建一个图像模式,如果您单击图像,它会创建放大的预览。我有来自服务的三个图像,我使用 *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
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

更新: 按照建议,我将模态 div 移到了 for 循环之外。我修改了 CSS 来阻止屏幕,这样我也可以将其保留在 for 循环内,并且用户不会注意到所有图像都已显示。但是,显示的图像始终是 for 循环的最后一个图像。因此,我要么 1) 将 div 模态放在 for 循环内,但弄清楚如何防止它选择 for 循环中的最后一个 url,要么 2) 我将 div 模态放在 for 循环外部,但将 {{randomULR}} 传递给 img源代码。

Zer*_*lve 5

你不应该(几乎)永远不要将 jQuery 与 Angular 一起使用。Angular 基本上可以完成 jQuery 所做的一切。

在你的情况下,你可以将点击的图像作为参数函数传递: (click)="show(randomURL)"这样你就知道 wicht url 被点击了。您必须将模态框放在 ngFor 之外,否则您将有 3 个模态框。

我可以给你的一个技巧是使用 Angular Material Dialog 或 CDK Dialog 来显示模态而不是你自己的。