angular4中的双向绑定问题

时间:2018-01-25 09:24:57

标签: javascript angular two-way-binding

我无法在angular4工作中获得双向绑定。这是组件代码。

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

@Component({
  selector: 'app-date-selector',
  templateUrl: './date-selector.component.html',
  styleUrls: ['./date-selector.component.css']
})
export class DateSelectorComponent implements OnInit {

  private statDate: Date;

  constructor() { }

  ngOnInit() {
    this.statDate = new Date()
  }

  goToPreviousDay(): void
  {
    console.log("previous day clicked");
    this.statDate.setDate(this.statDate.getDate() - 1);
    console.log(this.statDate);
  }

  goToNextDay(): void
  {
    console.log("next day clicked");
    this.statDate.setDate(this.statDate.getDate() + 1);
    console.log(this.statDate);
  }
}

我指的是像我这样的部分中的statDate。

<div>
    <a><span class="glyphicon glyphicon-chevron-left" (click)=goToPreviousDay()></span></a>
    <span class="text-center text-muted" [(innerText)]="statDate"></span>
    <a><span class="glyphicon glyphicon-chevron-right" (click)=goToNextDay()></span></a>
</div>

控制台日志显示statDate正在更新,但同样没有反映在UI中。

2 个答案:

答案 0 :(得分:0)

有几个问题需要指出。

角度绑定

在你的情况下,由于我们谈论的是跨度,你需要的只是单向绑定。在Angular中有几种方法可以做到这一点。

最常见,最简单,最简单的方法是使用interpolation。你也试图显示一个日期,所以你应该像这样使用Angular的DatePipe

<span>{{statDate | date}}</span>

这将使用多个变量打印您的日期,以便按照您的需要对其进行格式化。

HTML事件绑定语法

HTML中的click event binding也应如下所示:

<span (click)="goToPreviousDay()"></span>

请注意"之后的(click)=,Angular代码在HTML / TS语法拼写错误上停止执行是很常见的,这可以解释缺乏UI更新。

结果

结合上面提到的所有内容,生成的HTML将是:

<div>
  <a>
    <span class="glyphicon glyphicon-chevron-left" (click)="goToPreviousDay()"></span>
  </a>
  <span class="text-center text-muted">{{statDate | date}}</span>
  <a>
    <span class="glyphicon glyphicon-chevron-right" (click)="goToNextDay()"></span>
  </a>
</div>

答案 1 :(得分:0)

而不是two-way binding,您需要的只是one-way binding

改变这个:

<span class="text-center text-muted" [(innerText)]="statDate"></span>

到:

<span class="text-center text-muted" > {{ statDate }}</span>