Angular 4 属性 获取绑定不显示任何内容

Angular 4 Property get binding does not show anything

我有以下代码

export class TestClass{
    private time: string = "Test";

    public get TimeFormatted(): string {
        return this.time;
    }
}

在我的模板中

   <span>{{item.TimeFormatted}}</span>

但 html 中没有显示任何内容。

我猜你只是像下面这样在你的请求中映射模型。

let Array<TestClass> arr = response.json();

如果是这样,这不会影响在您的模型中实现的任何方法。 要使用您的模型方法,您需要从 Class 启动一个新对象并映射其属性。如果你在 TS 中启动一个模型,函数将被正确添加,如果你只是从你的请求中解析它,属性将像正常一样访问,但你的方法不会被添加,因为你的对象没有被启动,它只是被解析。

const newArr = new Array<TestClass>();
arr.foreach(item =>{
  let newItem = new TestClass();
  //mapping stuff 
  newArr.push(newItem);
});

如果你想使用 getter 和 setters,试试下面的代码。每次更改时间时,都会调用 setter 函数,您可以对其使用任何条件。您还可以在此处查看工作版本 https://stackblitz.com/edit/ionic-getters-setters

TS文件

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public _time: string;
  public password : string;


  constructor() {
    this._time="Test";
    this.password="password";

  }


    public get time(): string {
        return this._time;
    }

    public set time(value) {
      alert("set");
      if(this.password==="password"){
    this._time = value+"verified";
      }
  }

}

HTML代码

<input type="text" [(ngModel)]="time" />