首页 > 解决方案 > 无法在 div onclick 中使用方法

问题描述

我有一个角度示例,下面是我的app.component.ts文件:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  title = 'Core Helper';
  
  constructor(private router: Router) { 
    // this.router = Router;
  }

  navigate() {
      this.router.navigate(["docs"]);
  }
  }

app.component.html

<div id="releasenotes" onclick="navigate()">Release Notes</div>

当我调用此方法时,它会引发以下错误:

dashboard:27 Uncaught ReferenceError: navigate is not defined
    at HTMLDivElement.onclick (dashboard:27)

我不知道如何解决这个我试过如下

 document.getElementById('releasenotes').addEventListener("click", this.navigate);

在这种情况下,路由器未定义

标签: javascriptangularroutingnavigation

解决方案


点击处理程序的角度语法写成(click)="methodName()"

将 app.component.html 代码从

<div id="releasenotes" onclick="navigate()">Release Notes</div>

<div id="releasenotes" (click)="navigate()">Release Notes</div>

推荐阅读