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

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

问题描述

我目前正在构建一个 Angular 网站.我使用 *ngFor 循环创建了几个组件.每个创建的组件都有一个鼠标事件,应该用它打开一个 MatDialog (MatDialog).问题是对话框没有正常打开,里面的按钮也不起作用.但是,一旦我删除 *ngFor 循环并仅表示第一个元素,对话框就会完美运行.有谁知道这个问题以及如何解决它或 *ngFor 循环的替代方法?

不起作用:

<div (mousedown)="openMatDialog($event)" class="title">{{item.title}}</div>

功能:

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

函数 openMatDialog(e):

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

提前致谢

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

解决方案

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

<块引用>

解决方案:将 .html 模板中的 form.controls.credentials?.value 替换为 form.get('credentials').controls 即可.之后,垫子按钮再次在 *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?

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

解决方案

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.

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

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