Reactive Form value is not displaying in view because of FormControlName issue

I have successfully retrieved data from the database and need to pre-fill an update form with preset values. The issue I am facing is that when I add FormControlName to the input field, it removes the preset values. I have tried using setValue and patchValue methods but to no avail. Any suggestions on why this might be happening or a possible solution? Thank you in advance.

        
        <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
          <div class="snippet-code">
            <pre class="snippet-code-js lang-js prettyprint-override"><code>         
             ngOnInit() {
                 this.currUserId = this.userId$.value;
                 this.authService
               .findOne(this.currUserId)
                .pipe(map((user: User) => (this.currentUser = user)))
                .subscribe();
                }
             
                  <div class="tab-container" *ngIf="currentUser">
      
                   <form [formGroup]="accountForm" (ngSubmit)="submit()">
                    <ion-card class="personal-form">
                   <h3>Personal Details</h3>
                   <div class="form-input">
                   <label>FirstName</label>
                   <input
                   formControlName="firstName"
                   type="text"
                     value="{{currentUser.firstName }}"
                       />
                    </div>
          
                   <div class="form-input">
                    <label>surname</label>
                    <input
                    formControlName="surname"
                   type="text"
                   value="{{ currentUser.surname }}"
                 />
                  </div>
              </form>
          </div>
                                 

Answer №1

Try using the "formBuilder" instead of directly passing a value in the input field.

constructor(
  ...
  private _fb: FormBuilder,
){}

ngOnInit() {
  this.accountForm = this._fb.group({
      firstName: [''],
      surname: [''],
  });
  this.getCurrentUser();
}

getCurrentUser() {
      this.currUserId = this.userId$.value;
      this.authService
            .findOne(this.currUserId)
            .subscribe((user: User) => {
                 this.currentUser = user;
                 this.accountForm.patchValue(this.currentUser);
       });
  }
}

Make sure to eliminate both instances of value="{{currentUser.firstName }}" from the HTML form code.

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

When determining the extent to which client-side code should be utilized

As I work on developing a website with an extensive admin section, I am contemplating the amount of logic to incorporate on the client side. Using Ruby on Rails, I have the option of generating admin pages solely server-side with light client-side code for ...

I came across a forum where someone mentioned encountering a similar issue but unfortunately, no solution was provided. Currently, I am working on setting up a reaction roles system but despite embedding the message, the role is not being

I am currently working on setting up a reaction roles system for my Discord server, but I have encountered a significant issue that may seem minor to most. The problem is that although my bot successfully sends embeds with corresponding emojis for the ro ...

Utilize JavaScript and jQuery to locate a particular character within a string and move it one position back in the sequence

Can you locate a particular character within a string and move it to the position before? For instance: Consider the following string: Kù Iù Mù The desired output is: ùK ùI ùM ...

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Using v-on:click to dynamically update multiple sections of content in a Vue.js and Liquid environment

Whenever I click on a button, I want the text and image to change. I attempted to do this but encountered difficulties in updating multiple elements simultaneously. {% for variant in product.variants %} <label for="variant_{{- variant.id }}"&g ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Performing an AJAX call using jQuery within a PhoneGap application to communicate with a Node JS server

I've searched everywhere online for a practical demonstration of a jQuery AJAX call to a Node JS server, but to no avail. Typically, a jQuery AJAX request to a PHP server follows this format: $("button").click(function() { $.ajax({url: "http://w ...

Using React to display data from a nested JSON object in a table

I am currently working on parsing a JSON object into a table using React. However, I am facing an issue with utilizing the .map() function to create a row for every unique combination of course code, name, transferable_credits, transferable_credits -> i ...

Acquire information from a Card using Oracle Apex

I have a Card Regions that showcases some of my tables. I'd like each card to redirect to a specific page based on a number (the "page_table" number corresponds to the page it will redirect to). Below is the Query for the Cards Region: SELECT table_n ...

Is it achievable to dynamically generate new pages on initial load in NextJS?

Right now, I am utilizing getStaticProps and getStaticPaths to pre-render a specific number of articles before my website goes live. This method works effectively, but if a new article is created and displayed on the front page while the site is still acti ...

Design a personalized .OBJ / .MTL file and showcase it using the power of three.js

I attempted to create a basic blender model, export it to .obj/.mtl, and then render it with three.js. However, I am experiencing an issue. I have downloaded and uploaded the official three.js demo, and the objmtl-loader is functioning properly with the or ...

JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows: $(document).ready(function(){ $(window).scroll(function(){ if ($(thi ...

The date selected in the date picker does not display in the view until the calendar is opened

I am currently working with two date pickers named startDate and endDate. My goal is to set up a basic date validation system where the start date cannot come after the end date. The main requirement is that if the user selects an end date that is earlier ...

Merging two promises into a single promise in Angular

In my application, I am facing a challenge with implementing a method named loadAll. What I need to accomplish is to make calls to 2 different HTTP methods in order to load the necessary data. Both of these methods return promises. However, when I attem ...

Encountering the error message 'array expected for services config' within my GitLab CI/CD pipeline

My goal is to set up a pipeline in GitLab for running WebdriverIO TypeScript and Cucumber framework tests. I am encountering an issue when trying to execute wdio.conf.ts in the pipeline, resulting in this error: GitLab pipeline error Below is a snippet of ...

How can I fetch data from SQL using JavaScript based on a specific value in PHP?

My application is built using the Yii2 framework. Within my application, there is a view.php file that consists of an element and a button. The element, <div id="userId">, contains the user's login ID, and I aim to use the button to re ...