Angular中的* ngFor和MatDialog问题 [英] Problems with *ngFor and MatDialog in Angular

查看:157
本文介绍了Angular中的* ngFor和MatDialog问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建立一个Angular网站.我使用* ngFor循环创建了几个组件.每个创建的组件都有一个鼠标事件,通过该事件可以打开MatDialog( MatDialog ) .问题是该对话框无法正确打开,并且内部的按钮不起作用.但是,只要删除* ngFor循环并仅表示第一个元素,该对话框就可以正常工作. 有谁知道这个问题以及如何解决这个问题或* ngFor循环的替代方法?

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?

不起作用:

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

功能正常

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

openMatDialog(e)函数:

Function openMatDialog(e):

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

预先感谢

解决方案:在* ngFor循环中使用 trackBy

Solution: use of trackBy in the *ngFor loop

推荐答案

我过去也遇到过此问题.也许这会有所帮助: Mat-在让ng = index的* ngFor内单击按钮不会做出反应/触发动作

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

解决方案:将.html模板中的form.controls.credentials?.value替换为form.get('credentials').controls可以解决问题.之后,mat按钮再次在* ngFor内部起作用.

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.

这篇关于Angular中的* ngFor和MatDialog问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆