My Angular FormGroup patchValue method successfully applies changes, but the updates are not reflected on

I'm currently facing an issue with populating my Edit Form using user data emitted from an event in my code. Despite my efforts, the form is not displaying the information correctly.

export class EditUserComponent implements OnInit{
    
    constructor (private userService: UserService,
        private router: Router,
        private alertService: AlertService,
        private formBuilder: FormBuilder) {
    }
    
    userModel: IEditUserModel;
    editUserForm:FormGroup;

    ngOnInit(): void {
        this.editUserForm = this.formBuilder.group({
            userName: ['123'],
            firstname: ['123'],
            lastname: ['123'],
            email: ['123']
        })

        this.userService.getEditUserInfoEvent().subscribe({
            next: (editUserInfo)=> 
            {
                this.userModel = editUserInfo,
                this.setEditFormEventValues(this.userModel)
                console.log(this.userModel)
            }
        })
    }

    private setEditFormEventValues(userModel: IEditUserModel) {
      this.editUserForm.patchValue({
        userName: userModel.userName,
        firstname: userModel.firstname,
        lastname: userModel.lastname,
        email: userModel.email
      })
    }

The placeholder "123" values are just for testing purposes. The user information event is triggered during OnInit. When I check the values at the final patchValue method bracket, I see the updated info like Foncho123 as my new username value from the event subscription. However, the actual form input fields remain unchanged. Is there something important that I might be overlooking? Here's a snippet of my HTML view template, where all input fields follow a similar structure.

<form [formGroup]="editUserForm">
    <label for="uname">Username</label>
    <input type="text" id="uname" name="username" formControlName="userName">

Answer №1

Utilize the change detection trigger

export class EditUserComponent implements OnInit{
    
    constructor (private userService: UserService,
        private router: Router,
        private alertService: AlertService,
        private formBuilder: FormBuilder
        private cdRef: ChangeDetectorRef) {
    }
    
    userModel: IEditUserModel;
    editUserForm:FormGroup;

    ngOnInit(): void {
        this.editUserForm = this.formBuilder.group({
            userName: ['123'],
            firstname: ['123'],
            lastname: ['123'],
            email: ['123']
        })

        this.userService.getEditUserInfoEvent().subscribe({
            next: (editUserInfo)=> 
            {
                this.userModel = editUserInfo,
                this.setEditFormEventValues(this.userModel)
                console.log(this.userModel)
                this.cdRef.detectChanges();
            }
        })
    }

    private setEditFormEventValues(userModel: IEditUserModel) {
      this.editUserForm.patchValue({
        userName: userModel.userName,
        firstname: userModel.firstname,
        lastname: userModel.lastname,
        email: userModel.email
      })
    }

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 using `require('backbone')`, the returned object can vary depending on the file it is called in

backbone1.js var backbone1=require('backbone'); window.backbone=backbone1; backbone2.js console.log(window.backbone===require('backbone')); Why is the condition returning false. Shouldn't it return the same object everytime? E ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

Exploring AJAX GET requests and JavaScript capabilities

Just starting out with javascript and I'm a bit confused about how to solve a particular issue. Hopefully, the example below can help explain my situation: let tasks = { '04-23-2018' : '<a href="http://tympanus.net/codrops/201 ...

A password verification tool is indicating that the combination (0,0,0) can unlock, however, the given password does not

import React ,{useState}from 'react'; import './App.css'; function App() { const password =[2,2,3]; const [digits ,setDigits]=useState[0,0,0]); const [isUnlocked,setIsUnlocked]=useState(false); let setDigitAtIndex=(digit,idx ...

Guide to transferring information from a Complex Form in nodejs and express to MongoDB

I am a newcomer to node.js and express. Currently, I am working on creating a Business Card Generator application using nodejs, express, and MongoDB. I have set up a multi-step form in ejs and now I am looking for guidance on how to store the input data ...

The Angular selector is unrecognized: double-check that it belongs to the current module if it is an Angular component

After creating a component, I attempted to utilize it in another component by specifying its selector in the display segment. <app-component1></app-component1> However, I encountered a compile error. Upon reviewing the imports in the modules, ...

Troubleshooting issues with the 'date' input type feature on mobile devices

When I use the following code: <input type='month' ng-readonly='vm.isReadonly' required min="{{vm.threeMonthsAgo}}" max='{{vm.oneMonthAhead}}'/> I am experiencing some difficulties on mobile devices that do not occur o ...

Error message displaying "Invalid ID attribute in HTML 5 input"

On my website, I have a page with multiple items, each containing an HTML5 input field. Whenever a user changes the value of the input, it triggers an AJAX call to the server. The server then responds with JSON data, including an array of items that have ...

What is the solution for correcting the caret position in the Notification box?

I've encountered an issue with my Bootstrap dropdown notification system. I've noticed that the caret, which is intended to be positioned below the message icon, often moves away from it when viewed on different devices or screen sizes. Is there ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...

html The "download" attribute causing a new tab to open rather than initiating a

I have a website built with Angular 4, where users can download images from an Amazon S3 bucket. However, I encountered an issue wherein instead of downloading the image, it opens in a new tab. I've tested this problem on different browsers such as Fi ...

Updating multiple records in Node.js with mongoose using a file as the source of data

I have a CSV file that contains my data, and I am looking to perform a bulk add/update operation. exports.add_questions_from_file = function (file_path, surveyid, callback) { var U = [{}]; fs.readFile(file_path, 'utf8', function(err, dat ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

I am looking to connect the contents of a subfolder page with a page located in the main folder

I need to redirect the login page located in the subfolder signup to the index page within the main folder called web. The web folder contains both the index page and the signup folder, while the login page resides in the signup folder. What steps should ...

Strategies for successfully passing mock dates as event values when unit testing in Angular

I have a function that requires date data from a datepicker event. I am using matdatepicker for selecting a date from the UI. I need help passing the date event value to my onDateSelected() function. Could someone assist me in passing the date event valu ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Verify if the form has a checkbox and a correctly formatted email address is not functioning as

Implementing jQuery to ensure a valid email address is entered in the input field and a checkbox is checked before showing a modal. Below is the code snippet: // Display modal when correct info is provided $('.hero--input_button').click(functi ...