【问题标题】:ANGULAR.js passing function from one component to anotherANGULAR.js 将函数从一个组件传递到另一个组件
【发布时间】:2021-10-04 20:36:22
【问题描述】:

我正在尝试使用 angular 12 构建一个 pokedex 项目。

我想在我的 pokemon-list.component.html 中传递一个 openDialog() 函数

但是 openDialog() 是在一个名为 Dialog 的单独组件中定义的。 我在下面附上了项目结构。

这是我得到的错误: (index):1 Uncaught ReferenceError: openDialog is not defined 在 HTMLButtonElement.onclick ((index):1)

这就是我所做的: 在我的列表组件的html文档中

<button id="button" onclick="openDialog()">More Stats</button>

在 dialog.component.ts 中

import { Component } from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import { BehaviorSubject } from 'rxjs';



@Component({
  selector: 'app-dialog',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.css']
})
export class dialogComponent {

  constructor(public dialog: MatDialog) { }

  public openDialog() {
    this.dialog.open(dialogComponent);
    
  }
}

我的最终目标是在单击按钮后显示一个对话框

【问题讨论】:

  • Angular 无法识别 onclick 事件。它必须是(click)。试试:&lt;button id="button" (click)="openDialog()"&gt;More Stats&lt;/button&gt;.

标签: angular typescript angular-ui-router


【解决方案1】:

如果此代码在pokemon-list.component.html 中:

<button id="button" (click)="openDialog()">More Stats</button>

那么,我认为这个函数:

public openDialog() {
    this.dialog.open(dialogComponent);
}

应该在pokemon-list.component.ts 中。这样,当点击按钮时,openDialog函数将被调用并打开dialogComponent

【讨论】:

  • 很高兴听到它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2018-05-02
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
相关资源
最近更新 更多