4

I'm currently building an Angular website. I create several components using a *ngFor loop. The created components each have a mouse event with which a MatDialog should be opened (MatDialog). The problem is that the dialog does not open properly and the buttons inside do not work. However, as soon as I remove the *ngFor loop and only represent the first element, the dialog works perfectly. Does anyone know this problem and how to fix it or an alternative to the *ngFor loop?

Does not function:

<div *ngFor="let item of elements">
       <div (mousedown)="openMatDialog($event)" class="title">{{item.title}}</div>
</div>

Does function:

<div>
    <div (mousedown)="openMatDialog($event)" class="title">{{elements[0].title}}</div>
</div>

Function openMatDialog(e):

openMatDialog(e) {
    const matDialog = this.dialog.open(
        SettingsDialogComponent, { hasBackdrop: true }
    );
}

Thanks in advance

Solution: use of trackBy in the *ngFor loop

ines
  • 234
  • 4
  • 15

1 Answers1

2

I had this problem in the past as well. Maybe this will help: Mat-Button click inside a *ngFor with let index = index does not react/fire action

The solution: Replace the form.controls.credentials?.value to form.get('credentials').controls in the .html template does the trick. After that the mat-buttons are working inside the *ngFor again.

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
  • I am not sure how to use it now because I do not use
    . Can you explain that to me more exactly?
    – ines Dec 12 '19 at 15:01
  • `form.controls.credentials?.value` was received from a getter whereas the other value `form.get('credentials').controls` got me the direct reference. Maybe you can check this. – Ling Vu Dec 12 '19 at 15:11
  • No one can reproduce your issue. You are refering to values where we don't have any context. – Ling Vu Dec 12 '19 at 15:32
  • If you expect a proper answer and we should expect a proper question. – Ling Vu Dec 12 '19 at 15:32
  • Sorry, you were completely right. In the link you have sent me you also called the possibility with trackBy, which has solved my problem completely. Thanks a lot! – ines Dec 12 '19 at 16:01