Vinícius Santos
Vinícius Santos

Reputation: 70

How to open a angular 2 material modal when another modal is closed

I have a list called medicoesSelecionadas Selected and I need to open a modal using each element of the list, but the code can only open another modal when the previous one is closed.

I tried this code:

this.medicoesSelecionadas.forEach(medicao => {
  let historicoEmpreiteiro;
  this.loading = true;
  console.log(' ENTORU AQUI ')
  this.medicaoEmpService.ObterHistoricoEmpreiteiro(medicao.id)
    .subscribe(result => {
      this.loading = false;
      historicoEmpreiteiro = result;
      const refDialog = this.dialog.open(DescontoEmpreiteiroComponent, {
        data: { historicoEmpreiteiro: JSON.stringify(historicoEmpreiteiro) }
      });

      refDialog.afterClosed().subscribe(r => {
        console.log('Entrou closed');
      });

    });
    console.log(' ENTORU ALI ')
});

But the problem is, foreach opens all modals in the same time

Upvotes: 0

Views: 486

Answers (1)

dmcgrandle
dmcgrandle

Reputation: 6070

Assumption: this.medicoesSelecionadas is an array of objects

As long as this.medicoesSelecionadas array is not very long, I would probably solve this with recursion. Assuming your code above is within a function called 'existingFunc()', I would do something like the following:

existingFunc() {
    this.recursiveFunc(this.medicoesSelecionadas);
}

recursiveFunc(medicoesSelecs: Array<Object>) { // replace this type with the correct one
    if (medicoesSelecs.length > 0) {
        let medicao = medicoesSelecs.shift(); // remove first item from array
        let historicoEmpreiteiro;
        this.loading = true;
        console.log(' ENTORU AQUI ');
        this.medicaoEmpService.ObterHistoricoEmpreiteiro(medicao.id)
            .subscribe(result => {
                this.loading = false;
                historicoEmpreiteiro = result;
                const refDialog = this.dialog.open(DescontoEmpreiteiroComponent, {
                    data: { historicoEmpreiteiro: JSON.stringify(historicoEmpreiteiro) }
                });

                refDialog.afterClosed().subscribe(r => {
                    console.log('Entrou closed');
                    this.recursiveFunc(medicoesSelecs); // call self with remaining array
                });
            });
        console.log(' ENTORU ALI ');
        }
    }
}

This will create some overhead since all the functions will remain in the stack until the last one is finally closed, so you need to be careful not to call with too big an array to start with.

Upvotes: 1

Related Questions