angular - 为什么`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() {
}
}
...“开始”确实在控制台中打印。那么为什么在按钮中它是未定义的呢?
解决方案
该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');
}
}
推荐阅读
- php - 获取所有可能安装的 php 版本的最佳方法
- javascript - 使用 JavaScript 的视频弹出窗口
- java - Oracle sql join 与 3 个表
- python - 我在这段代码中找不到 idel 有什么问题
- python - 在 Pandas 中组合数据帧而不考虑零
- asp.net-core-signalr - 从控制台客户端调用 SignalR Core,但 JWT 授权失败
- python - 用 Python 合并列表
- python - Peewee 和原始 SQL 创建语句
- regex - 货币金额的正则表达式,D 表示负数,C 表示正数
- php - Slim PSR-17 响应工厂