繁体   English   中英

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

[英]Using $(this) in angular *ngFor loop

我正在尝试创建一个图像模式,如果您单击图像,它会创建一个放大的预览。 我有三个来自服务的图像,我使用 *ngFor 显示所有三个图像。 但是,当单击一个图像时,所有三个图像都会放大。 我知道我可以使用 $(this) 所以点击 function 知道要放大哪个图像 url 但我不确定如何实现。 任何帮助将不胜感激。 如果我需要安装 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来源。

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

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

我可以给您的提示是使用 Angular 材料对话框或 CDK 对话框来显示模态而不是您自己的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM