Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
How to call the same angular component multiple times using querySelector

So I have a component called custom-modal.component. The HTML file looks like this:

<dialog id="custom-modal">
 <ng-content></ng-content>
</dialog>

In the .ts file I have

this.modal = document.querySelector('#modal-custom');

// Buttons listeners to showModal() and close() methods...

The problem comes if I try to call modal multiple times:

<button class="open-modal">See cards</button>
<button class="open-modal">See flowers</button>

<app-custom-modal>
  <app-cards></app-cards>
</app-custom-modal>

<app-custom-modal>
  <app-flowers></app-flowers>
</app-custom-modal>

So in Angular, this will end up doing:

<button class="open-modal">See cards</button>
<button class="open-modal">See flowers</button>

*** NOTE that there's two ***

<dialog id="custom-modal">
 <div> <h1> Cards title </h1> </div>
</dialog>

<dialog id="custom-modal">
 <div> <h1> Flowers title </h1> </div>
</dialog>

The querySelector is not going to work as it only selects the first one. I can do a querySelectorAll and loop through every modal but then I don't have a way to assign the button listener to display the correct modal (Or I don't know how to do that).

I don't know if there's a better way to solve this, I just want to make it full re-usable. Sorry for noob questions as I'm Junior developer. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

An important part of this is keeping in mind where you want to handle the open/close state of your dialog.

In this case you are doing it in the component that hosts the modal. What you could do is pass an Input, let's say visible, to the modal that indicates the open/closed state. You can also define an Output that notifies you if the modal was commanded to close from within the modal component.

I also recommend that you should use ViewChild in the modal component instead of document.querySelector(...). Note that with the use of ViewChild you will most likely have to use the AfterViewInit lifecycle hook.

.ts file of the CustomModalComponent

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, Input, Output, EventEmitter } from '@angular/core';
// ... the rest of import

@Component({
  // ... Component decorator props (selector, templateUrl, styleUrls)
})
export class CustomModalComponent implements OnInit, AfterViewInit {
  @ViewChild('modalRef') modalRef: ElementRef;
  @Input() visible: boolean;
  
  // Optional if you want to close the dialog from here and notify the parent (host)
  @Output() closed = new EventEmitter(); 

  constructor() { }

  ngAfterViewInit(): void {
    // Print the HTMLElement of the modal
    console.log(this.modalRef.nativeElement);

    // Do your thing
  }

  close() {
    this.closed.emit();
    // ...
  }

  // ... the rest of the component
}

.html of CustomModalComponent

<dialog #modalRef>
 <ng-content></ng-content>
</dialog>

Then when you want to use it in the ParentComponent

In your .html

<button class="open-modal" (click)="openCards()">See cards</button>
<button class="open-modal" (click)="openFlowers()">See flowers</button>

<app-custom-modal [visible]="visibleCards" (closed)="closeCards()">
  <app-cards></app-cards>
</app-custom-modal>

<app-custom-modal [visible]="visibleFlowers" (closed)="closeFlowers()">
  <app-flowers></app-flowers>
</app-custom-modal>

In your .ts

import { Component } from '@angular/core';
// ... the rest of import

@Component({
  // ... Component decorator props (selector, templateUrl, styleUrls)
})
export class ParentComponent {
  visibleCards: boolean;
  visibleFlowers: boolean;

  constructor() { }

  openCards() {
    this.visibleCards = true;
    // ...
  }

  openFlowers() {
    this.visibleFlowers = true;
    // ...
  }

  closeCards() {
    this.visibleCards = false;
    // ...
  }

  closeFlowers() {
    this.visibleFlowers = false;
    // ...
  }

  // ... the rest of the component
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda