为什么单击按钮时不调用组件功能

时间:2017-06-08 15:37:25

标签: angular typescript

当我点击按钮时,知道为什么console.log('hey');未在浏览器控制台中记录?

如果点击sub-component,我试图显示/隐藏<button (click)="hey">Click me!</button>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  public flag = false;
  public hey() {
    console.log('hey');
    this.flag = true;
  }
}

app.component.html

<button (click)="hey">Click me!</button>
<div *ngIf="flag">
  <sub-component></sub-component>
</div>

的index.html

<body>
  <my-app>Loading...</my-app>
</body>

1 个答案:

答案 0 :(得分:1)

你需要调用一个方法。

<button (click)="logThis('hey')">Click me!</button>
<div *ngIf="flag">
  <sub-component></sub-component>
</div>

然后在你的组件中:

logThis(msg) {
  console.log(msg);
}

事情是(click)是点击事件。你必须告诉他当事件触发时该怎么做。在这种情况下,我们正在调用logThis()

<强>更新

我没有看到您确实声明了hey()方法,而您忘记了()

我以为你试图直接传递一个字符串。我的坏!

无论如何,这可能对其他人有用! :d

相关问题