Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Cómo cerrar una sección al hacer clic en el exterior que proviene del bucle y alternar en angular 10

Tengo algunas imágenes y texto de información, por lo que cuando hago clic en la imagen, el texto de información específico se usa para alternar/mostrar. Además, si se abre el texto de información anterior, se ocultará y se mostrará el siguiente texto de información al hacer clic en cualquier otra imagen. Ahora mi requisito es cerrar el texto de información en el exterior si está abierto. Aquí está el código a continuación. https://stackblitz.com/edit/angular-mb2rmb?file=src%2Fapp%2Fapp.component.html

aplicación.componente.html

 <hello name="{{ name }}"></hello> <h3>How to show info of clicked image only</h3> <div *ngFor="let x of things; let i = index"> <img src="https://source.unsplash.com/200x200" alt="loading" (click)="clicked(i)" /> <div *ngIf="x.show"> <div class="names"> <div class="fullName">{{ x.data }}</div> <div>{{ x.data2 }}</div> </div> </div> </div>

aplicación.componente.ts

 import { Component,Renderer2,ElementRef,ViewChild } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { name = 'Angular'; previousIndex: number = -1; public show: boolean = false; @ViewChild('toggleButton') toggleButton: ElementRef; @ViewChild('menu') menu: ElementRef; clicked(index) { // Checking if same picture clicked or new if (this.previousIndex >= 0 && this.previousIndex != index) { // If new picture is clicked then closing previous picture this.things[this.previousIndex].show = false; } // Updating index this.previousIndex = index; this.things[index].show = !this.things[index].show; } public things: Array<any> = [ { data: 'information for img1:', data2: 'only the info img1 is displayed', show: false, }, { data: 'information for img2:', data2: 'only the info for img2 is displayed', show: false, }, { data: 'information for img3:', data2: 'only the info for img3 is displayed', show: false, }, ]; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

MÉTODO 1
Cambie la función en la que se clicked para tener el evento como parámetro

 (click)="clicked(i, $event)"

&

 clicked(index, event) { // Checking if same picture clicked or new if (this.previousIndex >= 0 && this.previousIndex != index) { // If new picture is clicked then closing previous picture this.things[this.previousIndex].show = false; } // Updating index this.previousIndex = index; this.things[index].show = !this.things[index].show; event.stopPropagation(); }

Agregue otra función para el host:

 hostClick(e) { this.things.forEach((element)=>{ element.show = false; }); }

y actualice el component meta con el evento de clic del host

 @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], host: { "(click)": "hostClick($event)" } })

Como referencia, ejemplo de trabajo para el método 1

Básicamente, event.stopPropagation(); evita una mayor propagación del evento actual para alojar eventos de clic. El evento de clic del host se activa en cualquier lugar dentro del host (componente).

MÉTODO 2
Importar HostListener al componente

 import { Component,Renderer2,ElementRef,ViewChild, HostListener } from '@angular/core';

y use HostListener para vincular la función

 @HostListener("click", ["$event"]) hostClick(event: any): void { this.things.forEach((element)=>{ element.show = false; }); }

actualice la función en la que se hizo clic igual que en el método 1

 (click)="clicked(i, $event)"

&

 clicked(index, event) {console.log(index); // Checking if same picture clicked or new if (this.previousIndex >= 0 && this.previousIndex != index) { // If new picture is clicked then closing previous picture this.things[this.previousIndex].show = false; } // Updating index this.previousIndex = index; this.things[index].show = !this.things[index].show; event.stopPropagation(); }

Como referencia, ejemplo de trabajo para el método 2

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!