0

I am not able to get the two way binding in angular4 working. Here is the component code.

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);
  }
}

I am referring to statDate in my partial like this.

<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>

Console log shows that the statDate is getting updated, but the same is not getting reflected in the UI.

2 Answers2

0

Several issues to be pointed out.

Angular Binding

In your case, since we're talking about a span, all you need is one-way binding. There are several ways to do that in Angular.

The most common, readable and simple way to do this would be with an interpolation. Also you are trying to display a date, so you should use Angular's DatePipe like this:

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

That will pretty print your date with several variables to format it like you want.


HTML event binding syntax

Also your click event binding in HTML should look like this:

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

Note the " after the (click)=, it is pretty common for the Angular code to stop its execution on HTML/TS syntax typos and that would explain the lack of UI update.


Result

Combining all that is mentioned above, the resulting HTML would be:

<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>
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
0

Instead of two-way binding, all you need here is one-way binding.

Change this:

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

to :

<span class="text-center text-muted" > {{ statDate }}</span>
Faly
  • 13,291
  • 2
  • 19
  • 37