Bidirectional data binding with Observable object

I have been trying to connect isSelected to an object wrapped in an observable. When I attempted this without the observable, it worked perfectly fine. However, within my component, I am facing an issue where measure.isSelected always returns false, even when the checkbox is checked.

          <tr *ngFor="let measure of criteriaSelectedMeasures$ | async ; let i = index">
            <td>{{measure.type}}</td>
            <td>{{measure.equipment}}</td>
            <td>{{measure.axis}}</td>
            <td>{{measure.direction}}</td>
            <td>{{measure.pr}}</td>
            <td>{{measure.section}}</td>
            <td>{{measure.agregation}}</td>
            <td>{{measure.measureType}}</td>
            <td>{{measure.qualification}}</td>
            <td>
              <p-checkbox name="criteria-measure-{{i}}" binary="true" [(ngModel)]="measure.isSelected"></p-checkbox>
            </td>
          </tr>

Within my component :

this.criteriaSelectedMeasures$.subscribe(list => {
            this.store.dispatch(new AddMeasureDefinitionsAction(list.filter(m => m.isSelected))); <-- here isSelected is always false
        });

I believe that two-way binding is not working correctly here because the async pipe or subscribing to the observable creates a different object with another reference.

Do you think I am correct? Is there a different approach I can take to resolve this issue? (perhaps utilizing ngModelChange?)

Answer №1

It is advisable not to alter an object retrieved from an observable. If you need to modify specific data points, consider passing them as an array and bind directly to them. Using observables to pass to a component is most effective when the component's role is solely to display the data without altering it.

Observables may not always be the optimal choice in Angular. They typically allow information to flow only one way and emitted objects should generally be treated as immutable to avoid potential issues.

Additionally, utilizing two subscriptions (one with |async and one direct) may not be ideal unless your source is protected against this scenario, such as using shareReplay.

An alternative approach, albeit somewhat awkward, is to create an @Output() measureSelectionChange in your component where you can relay the measure ID and new selection status when a checkbox is clicked. This way, something external to the component can handle the actual modification of the measure and update the set of measures accordingly.

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

Creating Algorithms for Generic Interfaces in TypeScript to Make them Compatible with Derived Generic Classes

Consider the (simplified) code: interface GenericInterface<T> { value: T } function genericIdentity<T>(instance : GenericInterface<T>) : GenericInterface<T> { return instance; } class GenericImplementingClass<T> implemen ...

Leverage HighCharts on numerous occasions

Hello there, I'm curious about utilizing the Highcharts library in my Angular application. I have 3 tabs (sale / rental / rental & sale), each with 3 identical diagrams that display different data from my API. Currently, my setup only works on t ...

Typescript for managing the Shopify admin API

Is there anyone who can confirm whether Shopify offers typescript definitions for their admin API? I'm specifically interested in finding types for Orders, Products, and Variants. I initially assumed that this package would have them, but it seems l ...

How can I validate a method for formGroup in Angular 2?

Below is a form I am working with: this.changePasswordForm = this.formBuilder.group({ 'passwordNew': ['', ValidationService.passwordValidator], matchingPasswords('passwordNew', 'passwordNewConfirmation')(this) ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Forwarding routes with Angular Router

My server has specific mappings for different URLs: / serves an Angular application with routing capabilities /admin serves a Django control panel for staff database updates /api and /api/... serve REST endpoints to handle queries and return JSON data I ...

Conceal the choice when aria-expand is in a deactivated state

I'm currently facing a challenge with hiding an option in mat-select only when aria-expanded is false. In the dropdown menu, I have both "Select All" and "Deselect All" options. However, when the menu is closed, it displays "Deselect All" by default ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...

Creating a versatile protractor framework to streamline multiple project implementations

There's a concept in the works for creating a 'protractor core' that will be utilized by various projects for UI testing. Currently, I have an Angular project called 'project1' with e2e tests (cucumber-protractor-typescript) that c ...

The page fails to load when redirected, however, it briefly displays the page upon clicking the back button before navigating back to the previous page

Currently, I am working with Angular 2 and encountering an issue when attempting to click on a link. The loading bar continues to progress without displaying the data or HTML content on the page. Furthermore, if I try to go back to the previous page, the i ...

Can the inclusion of additional parameters compromise the type safety in TypeScript?

For demonstration purposes, let's consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 const f2: F2 = f1 f ...

Utilizing a monorepo approach enables the inclusion of all *.d.ts files

Scenario: In our monorepo, we have 2 workspaces: foo and bar. foo contains the following files: src/file.ts src/@types/baz.d.ts The bar workspace is importing @monorepo/foo/src/file. While type-checking works for the foo workspace, it does not work fo ...

Click on the button to sort Angular data

Greetings! I am a newcomer trying to grasp the concepts of angularjs/typescript. I have compiled an array of fruits, displayed in an unordered list. My goal is to arrange them in descending order and implement a reverse search function to display the item ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

Exploring the implementation of a custom validator within an Angular service

I have been attempting to implement a custom validator to validate if an email is already in use. After consulting the documentation and reading various articles, I have come up with the following code: In my auth.service.ts file checkEmail(email) { ...

After changing routes in Angular 4, the application experiences decreased speed and a continual increase in the number of nodes, particularly noticeable in Chrome but not in Firefox

After switching routes multiple times, I noticed a decrease in the app's speed. Upon inspecting the 'performance + memory' section using Chrome debugger, I observed an increasing number of DOM nodes. It seems that the DOM nodes are not prop ...

Updating DynamoDB objects seamlessly in Lambda functions without any conflicts

I am currently working with example Objects that follow this interface structure: interface Car{ id: Number; name: String; tires: Wheel[] } interface Wheel{ id: Number; name: String; radius: Number; } My goal is to store these Car Objects in DynamoDB and ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...

The API call is failing when using getInitialProps in Next.js

I have been trying to retrieve data from an API using the getinitialprops method and axios However, it seems like my code is not working as expected. Here is a snippet of the relevant code in the file pages/index.tsx IndexPage.getInitialProps = async (ctx ...