首页 > 解决方案 > 为什么`console.log` 在按钮(单击)内不起作用?

问题描述

为什么这不起作用?

<button (click)="console.log('ok');">Display Detais</button>

它说

Cannot read property 'log' of undefined

但是console.log类构造函数中的 a 有效:

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

@Component({
  selector: 'app3-directives',
  templateUrl: './directives.component.html'
})
export class DirectivesComponent implements OnInit {

  constructor() { console.log('start') }

  ngOnInit() {
  }

}

...“开始”确实在控制台中打印。那么为什么在按钮中它是未定义的呢?

标签: angulartypescript

解决方案


console对象在模板中是未知的,因为它不是组件的公共属性。你可以做什么:

export class DirectivesComponent implements OnInit {

  // console is now known inside the template
  console = console;

  constructor() { console.log('start') }

  ngOnInit() {
  }
}

但是,我不推荐这种方式用于记录目的。日志记录应该仅用于开发,因此将其保留在组件中。也许是这样的:

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

...

click() {
  if (isDevMode()) {
    console.log('do some logging');
  }
}

推荐阅读