Problems with *ngFor and MatDialog in Angular

こ雲淡風輕ζ 提交于 2020-03-02 11:52:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/59306857/problems-with-ngfor-and-matdialog-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!