The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view.

The specific problem I'm encountering is that the field "Funcion" is not displaying the value:

https://i.sstatic.net/b5GeR.png

Below is a snippet of my HTML code:

<form #f="ngForm" [formGroup]="registros" class="fila-contenido">
                <div class="campos">
                    <!-- En Venta THIS IS OK-->
                    <label>¿En venta?</label>
                    <mat-radio-group formControlName="enVenta" aria-labelledby="example-radio-group-label"
                        class="example-radio-group">
                        <mat-radio-button value="1" class="example-radio-button">Si</mat-radio-button>
                        <mat-radio-button value="0" class="example-radio-button">No</mat-radio-button>
                    </mat-radio-group>
                </div>

                <!-- Activo THIS IS OK-->
                <div class="campos">
                    <label>¿Registrado?</label>
                    <mat-radio-group formControlName="activo" aria-labelledby="example-radio-group-label"
                        class="example-radio-group">
                        <mat-radio-button value="Si" class="example-radio-button">Si</mat-radio-button>
                        <mat-radio-button value="En Trámite" class="example-radio-button">En Trámite</mat-radio-button>
                        <mat-radio-button value="No Necesita" class="example-radio-button">No Necesita
                        </mat-radio-button>
                        <mat-radio-button value="No" class="example-radio-button">No</mat-radio-button>
                    </mat-radio-group>
                </div>

                <!-- Pais THIS IS OK-->
                <mat-form-field appearance="">
                    <mat-label>Pais</mat-label>
                    <mat-select formControlName="pais">
                        <mat-option *ngFor="let pais of selectedPaises" [value]="pais">{{pais}}</mat-option>
                    </mat-select>
                </mat-form-field>

                <!-- Funcion THIS IS NOT OK-->
                <mat-form-field appearance="">
                    <mat-label style=" font-weight: bold;">Función</mat-label>
                    <mat-select formControlName="funcion" required (selectionChange)=changeFuncion($event)>
                        <mat-option *ngFor="let funcion of funciones" [value]="funcion">{{funcion.Funcion}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>
</form>

Additionally, here is the TypeScript code:

ngOnInit(): void {

    this.getRegistros();


  }

getRegistros() {
    this.http.get<Registro>('http://localhost:7000/api/registros/' + this.service.getRow()).subscribe(data => {
      data.log = data.log.replace(/\\"/g, '"');
      console.log("formateo", JSON.parse(data.log));
      let convert = JSON.parse(data.log);

      this.registros.controls.enVenta.setValue(convert.enVenta); //this is OK
      this.registros.controls.activo.setValue(convert.activo); //this is OK
      this.registros.controls.pais.setValue(convert.pais); //this is OK
      this.registros.controls.funcion.setValue(convert.funcion); //this is not OK

});
}

Having tried various approaches, such as logging all the form values (which includes the missing value) and testing with ngOnInit and ngAfterViewInit cycles, I am still unable to resolve the issue. I also attempted to use patchValue() instead of setValue() without success.

If you have any suggestions or advice, I would greatly appreciate it.

Thank you.

Answer №1

When working with Angular, object identity is used to select options. It is important to note that the identities of items can change even if the data remains the same. This can occur, for example, when items are retrieved from a server using an RPC call, and the call is made again. In this scenario, even if the data has not changed, the new response will contain objects with different identities.

In order to address this issue, a compareFn function needs to be provided to the mat-select component using the compareWith input. This function informs Angular how to compare the values effectively.

Give this a try:

component.html

   <mat-form-field appearance="">
                <mat-label style=" font-weight: bold;">Function</mat-label>
                <mat-select formControlName="function" required (selectionChange)=changeFunction($event) [compareWith]="compareWithFunction">
                    <mat-option *ngFor="let function of functions" [value]="function">{{function.Function}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

component.ts

It is assumed that the funciones object includes an id property.

compareWithFunction(listOfItems,selectedItem){
     return listOfItems && selectedItem && listOfItems.id === selectedItem.id; ;
}

Answer №2

It seems like the issue lies within your template file:

Here is the updated template:

<mat-form-field appearance="">
                    <mat-label style=" font-weight: bold;">Función</mat-label>
                    <mat-select formControlName="funcion" required (selectionChange)=changeFuncion(funcion) [(ngModel)]="funcion">
                        <mat-option *ngFor="let funcion of funciones" [value]="funcion">{{funcion.Funcion}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>

Component:

funcion:any;

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

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...

Sort through the files for translation by utilizing a feature within Typewriter

I am looking to implement Typewriter in a project that involves translating many C# files into TypeScript using WebEssentials. Is there a way to configure the template so that only class files containing a specific attribute are translated in this mann ...

Ways to prevent websites from switching to landscape mode

Is there a way to prevent landscape mode on my website and restrict users to portrait mode, especially for devices with screen widths below 777px? I have custom headers that take up fixed position space of around 100px on the screen. If it is possible to ...

`How can I extract information from the internet?`

I am attempting to retrieve data from the following URL: . My focus is on obtaining the raw data series rather than the data presented in tables and charts. Although the website provides a button for downloading a .csv file, I am unsure of how to automat ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Using ngIf for binding

Trying to bind values based on conditions specified in *ngIf. However, when using the && operator within *ngIf, it seems to be behaving mysteriously. Sample Code: <div *ngIf="days.sunday == true"> <p class="circle ml-3" ...

Are you a skilled UI Designer looking to work with JHipster?

Just starting out with JHipster and I've generated my first Angular 2 project using JHipster 4.5.1. It's been an amazing journey so far! Now, I'm looking to customize the default JHipster generated Angular 2 pages and create my own custom p ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Updating Mongoose References

When updating the Kwizz model with the password from req.body and team ID from req.session, it currently replaces the existing teams array. However, I am looking to simply add 1 to the array instead. I have searched for a solution but couldn't find a ...

Sinon experiences delays during an AJAX call

I am working with Mocha Chai and Sinon to test a revealing module pattern and encountering a timeout failure. How can I effectively test a method that assigns variables from an AJAX request? Test.js (function () { 'use strict'; describe(&a ...

Exploring the typing for DefaultRootState in React Redux Connect

I'm currently in the process of upgrading to the latest versions of TypeScript, React, and Redux. However, I've encountered a compiler error when using the connect function in React Redux: According to the React Redux documentation, I typed my r ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

Is there a way to retrieve the headers from an HTTP response in JavaScript that wasn't initiated by an AJAX request?

I have a login page setup to send an HTTP post request to the server, which then redirects me to another page on the server in the response message. On this new page, I need to access the location header to obtain a specific value for future server tasks. ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...

retrieving dynamic information from beyond the subscribe function

In order to implement canActivate for user routes, I need to first verify the validity of the access token. Below is the approach I am taking: export class AuthGuard implements CanActivate { data:Array<Object>; constructor(private base: BaseServ ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...