Angular is failing to detect a change in the initial element of an array

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

Answer №1

Give this a shot - I made a slight adjustment to the code by commenting out a line in the middle. See if it works for you:

     const monday = this.generateMonday(date);
     //dates[0] = monday;
     const mondayDate = monday.getTime();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing a stateless React component with withRouter() using Enzyme and ways to pass the match parameter

I have a React functional component that I am testing and it is wrapped in withRouter from react-router-dom. The component's code structure is shown below. import * as React from 'react'; import { Switch, Route, withRouter, RouteComponentPr ...

Tips for updating the text content of an HTML input element during a unit test

I am currently writing unit tests for an Angular application and I am attempting to set the text content of an input element using a unit test written with Jasmine. <input type="text" id="accountid" class="form-control col-sm-3" [(ngModel)]="record.acc ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

Tips for successfully passing an array containing multiple values within the jsPDF body

I'm experimenting with jsPDF to showcase a list of products that users have ordered. I've managed to set up my columns and generate the PDF for download, but I'm facing some challenges with populating the body section. When attempting to sen ...

modify pseudo element's style in Angular based on a particular condition

I am trying to change the style of :before based on a condition. I attempted to implement the solution provided at , but it did not work as expected. Here is my code: .sender:before { content: ""; width: 0px; ...

What is the mechanism behind flatMap executing code in a synchronous manner?

Currently, I am utilizing flatMap because it has the ability to process asynchronous code synchronously, allowing values from previous results to be handled one-by-one. However, I am unsure of how this functionality is achieved since the documentation does ...

Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'] ...

Adding a new column to a PySpark dataframe array

I am working with a Dataframe that has 2 columns | VPN | UPC | +--------+-----------------+ | 1 | [4,2] | | 2 | [1,2] | | null | [4,7] | My goal is to create a new column called "result" that combin ...

When requesting URLs on the server via Http, they must be in absolute form

Recently, I developed an Angular Universal application using Angular2 where I made a request to the /category service. this.hsService.getCategories(AppConstants.BASE_URL_GET_CATGORIES).subscribe( resp => { if (resp !== null) { console.log(& ...

Back up your Firestore data automatically using scheduled cron jobs!

Recently, I utilized the firestore-backup-restore tool for backing up Firestore data and it worked seamlessly. However, I am unsure how to schedule this process using cron jobs or a similar method. As someone with no prior experience in utilizing cron jobs ...

Dealing with HTTPClient in Angular 4: The frustrating issue of consistently receiving error code 0

Hello, I'm facing an issue with Angular's HTTPClient. Due to using Ionic 3 and Cordova, I am unable to utilize JQuery, which is why I have resorted to using HTTPClient. The following lines are present in my code : var body = new URLSearchPara ...

The fuse box was to blame for triggering a GET request to http://localhost:4444/, resulting in the error message

I encountered an issue with fuse-box and P5.js where I received a GET http://localhost:4444/ net::ERR_CONNECTION_REFUSED. The complete code can be accessed on GitHub. The fuse.js file contains the following configuration: const { FuseBox, WebIndexPlugin ...

Determining the presence of an item from a one-dimensional array within a multi-dimensional array

array1D = ['book', 'aa', 'Ab', 'AB'] arrayMD = ['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr'] Is there a way to determine if any ...

Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There ar ...

Managing Image Files in Node.js-Express with MongoDB and Displaying Them in Angular8 Interface

This Employee Management System allows for the uploading and storage of profile images of employees in an API server with a defined path. The implementation involves the following steps: https://i.sstatic.net/JBgb0.png Step 1: Making an API Server Reque ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Retrieve the name of a property or field from an object with a specified type

I have an angular class that is injectable with a readonly property. I do not have control over the initialization of this class as it is meant to be used in a library. Consumers of this library can access these properties but are not allowed to modify the ...

Tips for creating cascading dynamic attributes within Typescript?

I'm in the process of converting a JavaScript project to TypeScript and encountering difficulties with a certain section of my code that TypeScript is flagging as an issue. Within TypeScript, I aim to gather data in a dynamic object named licensesSta ...

Navigating with Angular 2 [routerLink] while including route parameters

Currently, I am working on developing an application using angular 2. As part of this project, I am trying to pass parameters to the [routerLink] tag in order to create a link structure like the following: <a href="/auth/signup?cell=1654654654">< ...

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...