The form control name cannot be viewed in display mode

When using a reactive form to display information, I encountered an issue where one field in the form group was not rendering the value until the page was refreshed. Here is a simplified version of the code:

.ts file

private getPhaseParId(id: number) {
    this.phasesService.getPhaseParId(id)
      .subscribe(
        (phase: Phase) => {
          if (phase) {
            this.maPhase = phase;
            console.log("before updatePhaseFormulaire()",this.phaseFormulaire.get('predecesseur').value);
            this.updatePhaseFormulaire();                
            console.log("after updatePhaseFormulaire()",this.phaseFormulaire.get('predecesseur').value);    
          } else {
            // else block treatment
          }
        },
        erreur => {
          // error block treatment
        })
}

private updatePhaseFormulaire(): void {   
    this.phaseFormulaire.patchValue({
      id: this.maPhase.id,
      nom: this.maPhase.nom,
      predecesseur: this.maPhase?.predecesseur      
    })    
}

and .html snippet

<form [formGroup]="phaseFormulaire" class="needs-validation" novalidate>
  <div class="form-row">
    <select class="form-input heightFixed" id="predecesseur"
        formControlName="predecesseur"
        title="{{ 'phase.formulaire.predecesseur.input.infobulle' | translate}}">
        <option [ngValue]="null||undefined" *ngIf="phaseListe && phaseListe.length > 0">
          {{ 'phase.formulaire.predecesseur.placeholder.libelle' | translate}}
        </option>
        <option [ngValue]="null||undefined" *ngIf="!phaseListe || phaseListe.length === 0">
          {{ 'phase.formulaire.predecesseur.aucunPredecesseur.libelle' | translate}}
        </option>
        <option [ngValue]="predecesseur" *ngFor="let predecesseur of predecesseursListe | orderBy:'nom'" [attr.selected]="predecesseur.id == this.maPhase?.predecesseur?.id ? true : null">
          {{predecesseur.nom}}
        </option>
      </select>
  </div>
</form>

Despite setting up the code as shown above, the predecesseur formControlName does not display anything on the page initially. However, with console.log before and after the update function, the output shows:

  • before updatePhaseFormulaire: Phase {}
  • after updatePhaseFormulaire:
    {id: 1, nom: 'Admissibilité',statutOk: 'Accepté', statutKo: 'Refusé', …}

I have attempted to use ngAfterViewInit() but it did not resolve the issue. Does anyone have any ideas on how to fix this bug?

Answer №1

It is important to review and confirm that the FormControlName attribute is accurately assigned to the input field within your HTML template. It must correspond with the control's name in your form.

Answer №2

Make sure that the select options have a value of "objects" (you're equal to "predecessor"), not just a single string or number. It seems like you want to do something like this (make sure ngValue is set to predecesseur.id)

<option [ngValue]="predecesseur.id" 
         *ngFor="let predecesseur of predecesseursListe | orderBy:'nom'" ...>
          {{predecesseur.nom}}
</option>

Update: if we really want to assign a complex object, we have two options, check out the docs

  1. Set the formControl equal to the same object, like this:

    this.phaseFormulaire.patchValue({
                  id: this.myPhase.id,
                  name: this.myPhase.name,
                  predecessor:this.predecessorsList.find(x=>x.id==this.myPhase?.predecessor)
                })
    
  2. Use a compare function:

    <select [compareWith]="compareFn"  
         [formControl]="selectedCountriesControl">
       ...
    </select>
    
    compareFn(c1: any, c2: any): boolean {
        return c1 && c2 ? c1.id === c2.id : c1 === c2;
    }
    

Answer №3

My issue was resolved by swapping the [ngValue] attribute in the <option> element with: [attr.value]

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 code is throwing an error stating: "TransformStream" is not a recognized name

I'm encountering an issue with my socket.io code. It previously built without any problems, but now I am unsure about what changes have caused the build to fail. It seems that TransformStream, a native node library, is having trouble loading in Typesc ...

"Exploring Firebase features, what is the process for generating a query using UID as a reference point

I recently developed a function that assigns a UID to the database along with an item's state: changestate(item) { var postData = { state: "listed", }; var user = firebase.auth().currentUser; var uid = user.uid; var updat ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

I am eager to perform DOM manipulation similar to jQuery but within the context of Angular 6

Is there a way to modify the background color of the main div when a button is clicked? <div> <p>I'd like to be able to change the background color of the parent div by clicking a certain button. </p> <button (click)=" ...

Execute a batch file to initiate the npm start command

I'm currently working on an Angular application and I'm looking to streamline the startup process. Instead of manually running "npm start" in the console, I want to create a batch file that will automatically run "npm install" for me. Here is the ...

What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API. Here is my implementation for getStaticProps: export const getStaticProps: GetStatic ...

Angular 2 ngx-modal: A User-Friendly Modal Component

I have encountered an issue while trying to implement a modal form in my Angular application. Even though my code seems correct and I have installed ngx-modal as well as imported the ModalModule in my app.module.ts, the modal form is not responding. Any ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Gatsby, in combination with TSC, does not properly transpile the rest operator

I'm attempting to integrate TypeScript with Gatsby following the guidelines provided here. However, I am encountering an issue where the tsc command is failing to transpile the spread (...) operator and producing the error shown below: WAIT Compili ...

Angular end-to-end testing doesn't locate the tag until the timeout expires following a route change

Recently, I've been diving into the world of e2e testing. So far, everything has been going smoothly with my tests on the first page - checking the title, h1 tag text, and number of cards. The issue arises when I try to navigate to a second page using ...

Setting up domain or IP Address in Angular with Spring Boot: A step-by-step guide

I'm facing an issue with my Angular 11 application hosted in the public folder of a Spring project. The Spring project is running on port 8075, and when I access my application from localhost:8075, everything works perfectly fine. However, when I try ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

The issue of Angular Service Broadcast not functioning as expected when integrated with routing

When I subscribe to an event in Service, I am able to access the emitted data in another component. However, when I attempt to route the page, the data is being set in ngOnInIt() but after the routing process starts, it reverts back to its default state. T ...

Validate prop must consist of one of two functional components

I am looking to ensure that a prop can only be one of two different components. Here is what I currently have: MyComponent.propTypes { propA: PropTypes.oneOfType([ PropTypes.instanceOf(ClassComponentA) PropTypes.instanceOf(ClassCompon ...

I wonder if there is a more effective way to format serial numbers

Could there be a more streamlined solution for this code snippet I have? /** * Converts serial from '86FC64484BE99E78' to '86:FC:64:48:4B:E9:9E:78' * @param serial */ private formatSerial(serial: string): string { retu ...

The Angular language service is experiencing difficulties in VS Code when it comes to newly created components using the CLI

I am currently facing an issue with the angular language service in an older project that already has a few components created. The problem arises when trying to generate NEW components using the CLI. For instance, a new component generated today: https:/ ...

Utilizing an array of data to create a complex structure with nested

In my Next.JS React project using TSX files, I have set up a data file like this: const fieldMapping = { category:[ { title: "Category 1", Subtitle: ["Category 1", "Category 2"], SubSubTitle: ["Category ...

Are your forms acting out? React Hooks and Typescript collaboration might be the answer!

After spending months using class components, I decided to try out Hooks and Typescript for the first time. My current challenge is setting up a search bar as a controlled form. No matter what I do, I can't seem to achieve this. Additionally, when t ...