captainsac
captainsac

Reputation: 2490

Angular 4 Typescript - Construct Array of Dates of subsequent 7 Days

I want construct an array of 7 dates. those dates will be 7 subsequent days from a SelectedDate. I have written following code in Component.ts

public selectedWeekDates: Date [];

public selectedWeek: Date = new Date();

SetSelectedWeekDates(): void {
    var dte = new Date();
    dte = this.selectedWeek;
    for (let i: number = 1; i < 8; i++) {            
        this.selectedWeekDates[i - 1].setDate(dte.getDate() + i);
    }

}

my html is as follows

.
.
.
<ng-container *ngFor="let dates of selectedWeekDates">
    <div style="padding: 10px;">
        {{ dates| date:"dd" }}
    </div>
</ng-container>
.
.
.

I am getting below error in console

TypeError: Unable to get property '0' of undefined or null reference at xxxComponent.prototype.SetSelectedWeekDates (eval code:179:143)

May I know what is wrong in my code?

Upvotes: 2

Views: 3207

Answers (2)

Nabil Shahid
Nabil Shahid

Reputation: 1458

In your function, you are using setDate function on elements of this.selectedWeekDates while they are undefined. You should use this.selectedWeek or dte to get and set your dates as below:

SetSelectedWeekDates(): void {
    let dte: Date = new Date(this.selectedWeek);        
     for (let i = 1; i < 8; i++) {            
        this.selectedWeekDates[i-1]=new Date(dte.setDate(dte.getDate() + 1));
        }

}

Also instead of adding i after getDate(), add 1 as done above as setDate() function is incrementing dte by a day in every iteration which means dte is updated after every iteration.

Upvotes: 2

SiddAjmera
SiddAjmera

Reputation: 39442

Your selectedWeekDates is empty. Hence the error. Give this a try to fix it:

public selectedWeekDates: Date[] = new Array(7).fill(new Date());

public selectedWeek: Date = new Date();

SetSelectedWeekDates(): void {
    var dte = new Date();
    dte = this.selectedWeek;
    for (let i: number = 1; i < 8; i++) {            
        this.selectedWeekDates[i - 1].setDate(dte.getDate() + i);
    }

}

This should fix the current error that you're getting. I'm not really sure what it is that you're trying to achieve here. So you might need to fix your logic a bit. All I'm able to see on the screen is 27, 7 times.

Here's a Sample StackBlitz for your ref.

Upvotes: 0

Related Questions