首页 > 解决方案 > 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 中的这种形式是否不允许使用函数?

标签: angulartypescriptvariables

解决方案


这是因为this

thisinside 函数counter是它自己的。您需要按如下方式绑定您的:

function counter() {
  this.today = new Date();
}
    
setInterval(counter.bind(this), 1000);

推荐阅读