angular - ngOnInit 变量不会出现在模板端
问题描述
我的应用程序组件中有以下代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Day1';
public today;
ngOnInit() {
function counter() {
this.today = new Date();
}
setInterval(counter, 1000);
}
}
我的 HTML 模板是:
<div class="clocklocation">{{today | date:'shortTime'}}</div>
如果today = new Date();一切正常 不包含在任何类型的函数中。我在这里做错了什么?Angular 中的这种形式是否不允许使用函数?
解决方案
这是因为this
this
inside 函数counter
是它自己的。您需要按如下方式绑定您的:
function counter() {
this.today = new Date();
}
setInterval(counter.bind(this), 1000);
推荐阅读
- domain-driven-design - 将 CQRS 读取模型实现为聚合是一个好主意吗?
- python - 拆分和连接后,我没有找回所有的字符串
- php - 使用 phpmailer 库在 PHP 中 smtp connect() 失败
- julia - 如何在 Julia 中更改级别
- react-native - TypeError:当我在 createDrawerNavigator 中使用自己的组件作为 contentComponent 时,无法读取未定义的属性“默认”
- vue.js - 使用缩放插件在 chart.js 中获取当前缩放信息
- python - 执行我的自定义最大似然代码时出现意外行为。它跳转到未调用的函数
- vba - VBA - 如果将某些数字传递给另一个子,则溢出错误
- authentication - 如何在httpUnit中设置认证参数?
- java - oauth 2.0 没有弹簧启动