Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation.

One of the components in my application is responsible for displaying a form:

https://i.stack.imgur.com/p5KEU.png

The form comprises various fields, some of which are simple input fields while others are dropdowns populated with values retrieved from asynchronous services.

Here is the structure of the form:

<h1 mat-dialog-title>Add device data</h1>
<form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup)">
    <div mat-dialog-content>
        <p>
            <mat-form-field appearance="fill">
                <mat-label>Date</mat-label>
                <input matInput [matDatepicker]="picker" formControlName="date">
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>

                <mat-error *ngIf="formGroup.get('date')?.hasError('required')">
                    Date is required
                </mat-error>
            </mat-form-field>
        </p>

        <p>
            <mat-form-field appearance="fill">
                <mat-label>Flat</mat-label>
                <mat-select formControlName="flat">
                    <mat-option *ngFor="let flat of flatService.flats$ | async" 
                                [value]="flat">
                        {{flat.title}}
                    </mat-option>
                </mat-select>

                <mat-error *ngIf="formGroup.get('flat')?.hasError('required')">
                    Flat is required
                </mat-error>
            </mat-form-field>
        </p>

        <!-- Other form fields go here -->

    </div>
    <div mat-dialog-actions>
        <button mat-button (click)="onCancel()" type="reset">Cancel</button>
        <button mat-button [disabled]="!formGroup.valid" type="submit">Save</button>
    </div>
</form>

In my component's TypeScript code:

@Component({
    selector: 'app-dashboard-device-dialog',
    templateUrl: './device-dialog.component.html',
    styleUrls: ['./device-dialog.component.css']
})
export class DashboardDeviceDialogComponent implements OnInit {
    // Component properties and methods go here
}

Answer №1

After posting my query, I decided to take a quick stroll and surprisingly, within just five minutes, I stumbled upon an idea that was quickly validated by writing some code.

The issue lies in the equality of objects - I am using objects as values in this format:

<mat-option *ngFor="let flat of flatService.flats$ | async" 
    [value]="flat">
    {{flat.title}}
</mat-option>

In my model, I have properties of object type like so:

export interface DataRecord {
    date: Date
    flat: Flat
    ...
}

Since I cannot create a method to compare two objects (similar to Java), objects are being compared by reference (using == or ===). Consequently, the Flat object in the dropdown differs from the one in the record.

To resolve this, I opted to utilize identifiers instead of references:

export interface DataRecord {
    date: Date
    flat: string
    device: string
    ...
}

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

The module "node_modules/puppeteer/lib/types" does not contain the export "Cookie"

Currently facing an issue with puppeteer types. I am attempting to import the Cookie type, but it seems to be not functioning on versions above 6.0.0. import { Cookie } from 'puppeteer'; Here is the error message: /node_modules/puppeteer/lib/typ ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...

The ngOnInit lifecycle hook is not triggered by the Angular routerLink

In the component.ts file, you will find the ngOnInit function as shown below: ngOnInit() { this.locationService.getLocation().subscribe( locations => { this.locations = locations; }); } <a [routerLink]="['/locations-list&apo ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

Exploring Function Type in TypeScript: Utilizing both fat arrow and object literal type

Currently delving into the world of Typescript, I came across two methods for defining function types: using a fat arrow or an object literal. Here's an example: let myAdd1: (x: number, y: number) => number = function(x: number, y: number): n ...

What is the reason for the ngFor loop in Ionic 5 component not functioning properly?

I'm facing an issue with the *ngFor directive in one of my components. It's strange because it works fine in other components. Can anyone help me figure out what I might be doing wrong? @Component({ selector: 'app-age-picker', temp ...

Step-by-step guide on implementing a draggable component for selecting the year using React

I am looking to develop a draggable component in React without relying on any third-party library. Below, I have provided an image depicting how the component might look. Currently, my component code appears as follows: import React from 'react'; ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

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, ...

Is it necessary to specify the inputs property when defining an Angular @Component?

While exploring the Angular Material Button code, I came across something interesting in the @Component section - a declared inputs property. The description indicates that this is a list of class property names to data-bind as component inputs. It seems ...

Is it possible to implement multiple Datepickers in Angular Material?

Exploring this resource to add a datepicker to my webpage. I've taken the code snippet below from the provided link: <div class="item item-1" fxFlex="50%" fxFlexOrder="1"> <mat-form-field> <input matInput [matDatepicker] ...

Using the Angular JSON pipe with angular-datatables

I am currently utilizing angular-datatables to exhibit NoSQL de-normalized data in a grid format for visualization purposes. Within my dataset, I have several intricate nested JSON objects and I intend to showcase a specific cell with formatted JSON using ...

The process of automatically formatting Typescript has transformed into an unfortunate auto-discarding action

Typescript autoformatting has become a concerning issue. Whenever I input quoted strings (" or `), the code surrounding it seems to temporarily glitch, with other strings appearing as code. This problem has recently escalated, particularly with strings li ...

Angular version 16+ is incompatible with Three.js and does not function properly together

I am attempting to integrate three.js into my Angular 16 project and encountering the following error message: npm i @angular-three/core npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email&# ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

I'm having difficulty updating the Angular CLI version

I am currently running Angular CLI version 7.1.4 and I have been attempting to update to the latest version. However, each time I try to update, I encounter a multitude of errors. I have attempted using the command ng update @angular/core @angular/cli b ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

Is it possible to drive without nest.js?

I currently have a node-ts-express-setup that does not utilize nest.js. Unfortunately, the documentation and examples for drivine do not provide setup instructions without nest.js. Is there a way to use drivine without having to include nest as a dependen ...

At what point during the angular build process are devDependencies integrated?

In my angular project, I have the need to build it in two different ways - for two separate environments (DEV and PROD; both hosted on a corporate server) After researching online, I came across various interpretations regarding when the devDependencies ( ...