What is the reasoning behind triggering ValueChanges during initialization even when there are no changes detected?

I am working with a popup component that includes a mat-datepicker. When the user changes the date, I need to update this value in another control and ensure that the start and end controls are valid. However, due to a bug in the mat-date-range-input, I encounter issues. Specifically, when I open the datepicker for the third or fourth time, I receive the error message NG0100: Expression has changed after it was checked. This occurs because ValueChanges is triggered even without any actual changes being made yet. How can I resolve this issue?

  ngAfterViewInit() {

    this.range.get('start').valueChanges.subscribe(() => {
      this.updateFormattedDates();
      this.changeDetectorRef.detectChanges();
    });

    this.range.get('end').valueChanges.subscribe(() => {
      this.updateFormattedDates();
      this.changeDetectorRef.detectChanges();
    });
  }

updateFormattedDates() {
...
}

Answer №1

If you want to streamline the number of events, consider using rxjs's distinctUntilChanged. It may be that calling detectChanges() unnecessarily is triggering the warning message!

ngAfterViewInit() {
    this.range.get('start')?.valueChanges.pipe(
      distinctUntilChanged(),
    ).subscribe(() => {
      this.updateFormattedDates();
      this.changeDetectorRef.detectChanges();
    });

    this.range.get('end')?.valueChanges.pipe(
      distinctUntilChanged(),
    ).subscribe(() => {
      this.updateFormattedDates();
      this.changeDetectorRef.detectChanges();
    });
  }

Check out the stackblitz here

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

Guide to Conditionally Importing a Module in Angular

I am currently developing a module for Search integration. Instead of directly importing the SearchModule inside my app.module.ts file, I would like to implement a method where an API is called and the SearchModule is imported based on the API response. @N ...

Firebase Cloud Function Local Emulator Fails to Retrieve Data with Error 404

My goal is to locally trigger a Firebase Cloud Function using the emulator. However, every time I try, the function returns a 404 Not Found status code and a response body of Cannot Get. The function is deployed locally and visible on the UI, but it fails ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Exploring Angular2: A guide to incorporating dynamic properties with conditional logic

Currently, I am diving into Angular2. In the midst of my journey, I am facing the challenge of adding a property to a <select> only if the class property type is 'withName' If this condition holds true, the outputted select should be: < ...

The readiness status of the mongoose connection is resulting in a TypeError: Unable to access undefined properties (reading 'readyState')

I've been utilizing Mongo Memory Server for my unit tests successfully, but all of a sudden mongoose.connection is returning as undefined. This has left me completely baffled! I would have anticipated readyState to at least be 0. import * as mongoose ...

Ensure the type of a variable matches another variable

Can another variable function as a type guard? Consider the following code snippet: let foo: string | null = Math.random() > .5 ? null : 'bar' const otherProp = true const test = foo !== null && otherProp function foobar(x: string){} ...

Angular/Typescript: Getting the enum name instead of its value in a key-value pair

In my project, I have defined the interfaces Meal and Mealplan to handle data retrieved from an api. Every Mealplan includes key-value pairs, where each key corresponds to a day of the week and is stored in the enum Weekday. Therefore, each Mealplan contai ...

Can constraints be implemented for route parameters in Angular 4 routing?

I have a routing service that requires the language parameter to be first in the route. However, I am facing an issue where everything matches the :lang parameter. For example: /en/xxx /fr/xxx /en/yyy /fr/yyy To address this problem, I have added the ...

What is the most effective method for displaying indicators for in-flight requests in rxjs without causing side effects?

What is the best way to display a loading indicator for an ongoing request using RXJS (along with Angular2+) without causing side effects in the pipe() function? I've brainstormed some options. Is there a recommended approach or a better alternative? ...

The type does not contain a property named 'x' - Error in Promise syntax - TS2339

I encountered a problem while working with Typescript that I couldn't quite figure out. Although I came across similar issues in other topics, I'm still struggling to find a solution for my particular issue. I can easily log userCredential.user.m ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Conceal the sidebar once user is logged in

I need a dynamic webpage; upon loading the login page, the sidebar should be hidden and the login page should occupy the full width of the page. Once the user successfully logs in, the sidebar along with all components should be displayed. I've attemp ...

Classifying Union Types based on their distinct characteristics

There is a specific type with its own unique property (method) type Functions = { method: "connect", request: number, response: number, } | { method: "remove", request: string, response: string, } I aim to create a function that can handle inp ...

The element does not have a property named 'className' in the object type '{ props: ReactNode; }'

I am currently in the process of converting a Next.js project from JavaScript to TypeScript, and I encountered an issue: Property 'className' does not exist on type '{ props: ReactNode; }'. In JavaScript, I could access className from p ...

Is TypeScript's `readonly` feature a complete replacement for Immutable.js?

Having experience with various projects utilizing React.js, I have worked with Flux, Redux, and plain React apps using Context. Personally, I appreciate the functional patterns used in Redux but find that unintentional state mutation can be a common issue ...

Troubleshooting: Unable to Open Page with Google Material Button in Angular 5

Currently, I'm facing an issue with a button that is not opening to a new site despite following what seems like simple steps. <button mat-raised-button href="https://www.google.com/" color="primary">Connect with Stripe</button> I even a ...

Preventing specific directories from being imported in a Typescript project

I am intrigued by the idea of restricting files within a specific scope from importing files from another scope. Let's consider this example: Imagine we have the following project structure: project/ ├── node_modules/ ├── test/ ├── ...

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Determine the numerical value of an input field by the option chosen in a dropdown

I want to increment the totalValue by 50 if the dropdown value is set to true. <div class="col"> <label class="form-label">Emergency</label> <select class="form-select" name="emergency" id=&q ...