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