【问题标题】:Can't use method in div onclick无法在 div onclick 中使用方法
【发布时间】:2020-04-29 22:34:48
【问题描述】:

我有一个角度示例,下面是我的 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);

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

【问题讨论】:

    标签: javascript angular routing navigation


    【解决方案1】:

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

    更改 app.component.html 代码
    <div id="releasenotes" onclick="navigate()">Release Notes</div>
    

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

    【讨论】:

    • 感谢兄弟...工作正常,但为什么 onclick 不起作用
    猜你喜欢
    • 2019-01-04
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    相关资源
    最近更新 更多