简体   繁体   中英

How to apply date in Angular2?

This is my function for todays date:

public static todaysDate(month: number): string {
        let day = new Date().getDate();
        let year = new Date().getFullYear();
        return "<span>" + day + ", " + "</span>" + year;
    }

and this is for tomorrows date:

public static tomorrowsDate(month: number): string {
            let day = new Date().getDate() + 1;
            let year = new Date().getFullYear();
            return "<span>" + day + ", " + "</span>" + year;
        }

In my HTML:

<ul class="text-left">
                <li><img src="../left.png"/></li>
                <li><span [innerHTML]="date"></span></li>
                <li><img src="../images/right.png"/></li>
            </ul>

I'm using [innerHTML] to render the HTML <span></span> tags.

This is my component:

this.date = Date.todaysDate(this.month);
this.dateTomorrow = Date.tomorrowsDate(this.month);

How can I apply tomorrows date and yesterdays date on right.png and left.png image clicks?

You need to bind click event for each buttons. Inside your click events, update your date variable. So your html will be like

<ul class="text-left">
    <li><img ng-click="yesterdayDate()" src="../left.png"/></li>
    <li><span>{{date}}</span></li>
    <li><img ng-click="tomorrowDate()"src="../images/right.png"/></li>
</ul>

It would seem better for your functions to return a date and to use a pipe in the interpolated string to reformat to the desired date format.

Something like this {{ date | date }}

Here is a plunker with an example: https://plnkr.co/edit/amip8h2pZMxeM7fi7yAZ?p=preview

I used buttons since I didn't have your images, but the code should basically be the same.

  <ul class="text-left">
       <li><button (click)="todaysDate(3)">left</button></li>
       <li>{{date | date}}</li>
       <li><button (click)="tomorrowsDate(3)">right</button></li> 
  </ul>

And the component functions:

export class App {
    name:string;
    date: date;
    constructor() {
       this.name = `Angular! v${VERSION.full}`
    }

  todaysDate(month: number): void {
    let day = new Date().getDate();
    let year = new Date().getFullYear();
    this.date = new Date(year, month, day);

  }

  tomorrowsDate(month: number): void {
        let day = new Date().getDate() + 1;
        let year = new Date().getFullYear();
        this.date = new Date(year, month, day);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM