In my Angular app, I am working on displaying a list of dates for the current week. Users should be able to view previous weeks by clicking a button, so I am using an Observable to update the array of dates and trying to display the updated array.
Although all items in the view are updated successfully, the first item in the array does not get updated. You can see an example on Plunker here
I have attempted to use *ngFor and the async pipe, as well as manually creating elements for each item in the array (as shown below), but both methods encounter the same issue. I am currently struggling to find a solution.
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Component({
selector: 'my-app',
template: `
<button (click)="previousWeek()">Prev Week</button>
<div>{{dates[0]}}</div>
<div>{{dates[1]}}</div>
<div>{{dates[2]}}</div>
`,
})
export class App {
name:string;
dates: Date[];
public $datesSource: Observable<Date[]>;
private datesSource: Subject<Date[]>;
constructor() {
this.datesSource = new Subject<Date[]>();
this.datesSource$ = this.getDatesWithObservable();
this.datesSource$.subscribe((dates) => {
console.log(dates);
this.dates = dates;
})
this.setDates(new Date());
}
setMonday(date: Date): Date {
const day = date.getDay() || 7;
if (day !== 1) {
date.setHours(-24 * (day - 1));
}
return date;
}
setDates(date: Date): void {
const dates = [
new Date(),
new Date(),
new Date(),
new Date(),
new Date(),
new Date(),
new Date()
];
const monday = this.setMonday(date);
dates[0] = monday;
const mondayDate = monday.getTime();
dates.forEach((date, idx) => {
console.log(idx);
date.setTime(monday.getTime() + (idx * 24 * 60 * 60 * 1000));
});
this.addDates(dates);
}
addDates(dates: Date[]): void {
this.datesSource.next(dates);
}
getDatesWithObservable(): Observable<Date[]> {
return this.datesSource.asObservable();
}
previousWeek(): void {
const day = this.dates[0].getDay() || 7;
const lastWeek = this.dates[0];
const days = 7;
lastWeek.setTime(lastWeek.getTime() - (days * 24 * 60 * 60 * 1000));
this.setDates(lastWeek);
}
}