When utilizing two-way databinding in Angular2+, the set function code does not run upon changes

My challenge is sharing an object between two components. The parent component holds the global instance of the object, and the two child components receive that instance through two-way data binding. However, despite the changes being propagated, the set function linked to that field is not being executed.

@Output() consultChanged = new EventEmitter<Consult>();
  @Input()
  set consult(consult: Consult) {
    console.log("Code to run when there is a change");
    this._consult = consult;
    this.consultChanged.emit(this._consult);
  }

Check out this example on stackblitz where the console.log is not triggered.

UPDATE: I am aiming for a behavior where all components sharing that variable call their setters when it changes (to update other variables with the new values). If you have alternative methods to achieve this, I am open to suggestions.

Answer №1

Changes are propagated when an instance is altered, however, the set function linked to that specific field is not triggered.

This issue arises because the setter is not invoked when an object is mutated in-place. This behavior is not unique to Typescript or Angular, but rather a characteristic of how setters function in Javascript.

If you want to ensure that the setter is executed, you should treat the data as immutable. Instead of

this.consult.property = "new value";

you should instead use

this.consult = {...this.consult, property: "new value"};

By doing this, the setter will be triggered as the reference itself has been altered.

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

What is the process for adding an element using Angular Material2 design?

I am in the process of creating a template where, upon clicking a button, I want to append specific elements. While I have successfully appended the elements using the code below, I am facing challenges with adding styles and integrating angular-material2 ...

Module '. ' or its corresponding type declarations cannot be located

While working on my project with TypeScript and using Cheerio, I encountered an issue when trying to compile it with TSC. The compiler threw the following exception: error TS2307: Cannot find module '.' or its corresponding type declarations. 2 ...

Having trouble updating Angular CLI

It appears that I have successfully installed version 9 as per the usual installation process. npm install -g @angular/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9abbca8acbcaaad99ebf7e1e1f7eb"> ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Extending Enums in Typescript: A Comprehensive Guide

How can you work with a list of constants or Enum? Here is an example: enum MyList { A, B } enum MyList2 { C } function process<T>(input:MyList | T):void { } process<MyList2>(123) // The compiler does not recognize that 123 ...

Connect a click event from one component to another component

Can Angular bind a click event dynamically from a component to another existing component on the page? Check out this image for reference. In my app, I have 4 simple components - a shell component that defines the layout, a header component (blue outline) ...

Creating an eye-catching animation in Angular 2+ by applying a checkbox check effect to each checkbox dynamically generated within a loop

When I integrated a CSS animation for checkbox "cards" into an Angular project, the transition ceased to function properly. I have limited experience with Angular and am trying to work with existing code. While I managed to get a basic animation working wi ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Creating a mock instance of a class and a function within that class using Jest

I am currently testing a class called ToTest.ts, which creates an instance of another class named Irrelevant.ts and calls a method on it called doSomething. // ToTest.ts const irrelevant = new Irrelevant(); export default class ToTest { // ... some impl ...

Steps for upgrading from Ionic framework v1.2.4 to Ionic framework v2.0.0-beta with npm

Currently, I am in the process of upgrading my Ionic framework from version 1.2.4 to the latest version 2.0.0-beta using the node package manager (npm). I stumbled upon a guide on the official documentation site that instructed me to execute this command ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Utilizing Arrays in Typescript within the Angular Framework

I have developed a Rest API that provides data to populate two drop-down lists in a form. The information retrieved from the API is grabbed by the Angular backend and assigned to the respective drop-downs. Rather than making separate Get requests for each ...

Unable to link the second array to the angular-dual-listbox

I am struggling to connect my JSON data with the Confirmed list in an angular-dual-listbox component created by czeckd. The source part appears correctly, but the Destination list is not displaying the expected results. I have set up a live example on Sta ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...

Error in Angular 4: No service available for MatDialogRef in Angular Material (webpack)

I have attempted various methods and followed the documentation instructions to set up Angular Material. Upon checking my console, I encountered the following error: core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for MatDialogRef ...

Upon the initial loading of GoJS and Angular Links, nodes are not bypassed

Hey there, I'm currently working on a workflow editor and renderer using Angular and GoJS. Everything seems to be in order, except for this one pesky bug that's bothering me. When the page first loads, the links don't avoid nodes properly. H ...

Is there a program available that can efficiently convert or translate JSON objects into TypeScript types or interfaces?

Can anyone recommend a tool that can easily convert a JSON object into a TypeScript type or interface? An example input would be something like this: I'm hoping to paste the JSON object into the tool and receive an output structure similar to: expor ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Error in Angular vendor.js (124116) related to Dom7 class in Internet Explorer 11

Every time I launch my project in IE11, I encounter an issue SCRIPT1002: Syntax error vendor.js (124116,1) Upon inspection of vendor.js at the specified line, I come across class Dom7 { constructor(arr) { const self = this; // Create array-lik ...

The `react-router-dom` in React consistently displays the `NotFound` page, but strangely, the active class for the home page does not get

Currently, I am utilizing "react-router-dom": "^6.4.1" in my application and encountering two main issues: Upon navigating to another page, the home page retains the active class, resulting in both the new page and the home page disp ...