What is the process of attaching data to a mat form field in Angular?

How can I show the data from an http request on a form field in Angular? I want the user to be able to edit the data and submit it. The email, firstname, etc. should display in the input fields.

When the edit button is clicked, I want the form field values to get populated with the data retrieved from getUserDetails like firstname, lastname, etc., instead of using {{this.data.emailAddress}} as shown below.

#init

ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe((params) => {
      this.userId = params.id;
      this.getUserGeneralDetails();
    });
  }

#constructor

 constructor(
    private _activatedRoute: ActivatedRoute,
    private _notificationService: NotificationService,
    private _userProfileService: UserProfileService,
    private _router: Router,
    private fb: FormBuilder
  ) {
    this.generalForm.disable();
    this.securityForm.disable();
  }

I only want to display the data on the form field when Edit is clicked.

 generalForm = new FormGroup({
    email: new FormControl(),
    fname: new FormControl(),
    lname: new FormControl(),
    phone: new FormControl(),
    companyName: new FormControl(),
    title: new FormControl(),
  });

New to Angular and looking for techniques and ideas. Thank you.

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


https://i.sstatic.net/j3EJB.png #template

 <div class="card" #generalCard>
            <span class="anchor" id="general"></span>
            <div class="card-header">
                <mat-icon class="card-icon">group</mat-icon>
                <div class="title">GENERAL</div>
                <div class="spacer"></div>
                <button mat-button *ngIf="generalForm.disabled" (click)="generalForm.enable()">
                    <mat-icon>edit</mat-icon> Edit
                </button>
                <button mat-button *ngIf="generalForm.enabled" (click)="generalForm.disable()">
                    Cancel
                </button>
                <button mat-stroked-button *ngIf="generalForm.enabled" (click)="saveGeneralFormChanges()">
                    Save Changes
                </button>
            </div>
            <div class="card-content" *ngIf="generalForm.disabled" >
                <div class="line-item">
                    <div class="title">EMAIL</div>
                    <div class="detail">{{this.data.emailAddress}}</div>
                    <mat-icon class="active" style="color:#00B0DB;">check_circle</mat-icon>
                </div>

                <div class="line-item">
                    <div class="title">EMAIL</div>
                    <div class="detail">{{this.data.emailAddress}}</div>
                    <mat-icon>check_circle_outline</mat-icon>
                    <button mat-button class="detail active">Resend welcome email</button>
                </div>

                <div class="line-item">
                    <div class="title">FIRST NAME</div>
                    <div class="detail">{{this.data.firstName}}</div>
                </div>

                <div class="line-item">
                    <div class="title">LAST NAME</div>
                    <div class="detail">{{this.data.lastName}}</div>
                </div>

                <div class="line-item">
                    <div class="title">PHONE NUMBER</div>
                    <div class="detail">+1 {{this.data.phoneNumber}}</div>
                </div>

                <div class="line-item">
                    <div class="title">COMPANY NAME</div>
                    <div class="detail">{{this.data.companyName || 'None'}}</div>
                </div>

                <div class="line-item">
                    <div class="title">TITLE</div>
                    <div class="detail">{{this.data.title || 'None'}}</div>
                </div>
            </div>

#GetUserData

getUserGeneralDetails() {
    this.isInProgress = true;
    this._userProfileService
      .getUserGeneralDetails(this.userId)
      .pipe(finalize(() => (this.isInProgress = false)))
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.data = res.data;
          }
        },
        error: (err) => this._notificationService.showError(err),
        complete: noop,
      });
  }

#field code

<div class="card-content" *ngIf="generalForm.enabled">
                <form [formGroup]="generalForm" class="generalForm">
                    <mat-form-field appearance="fill" class="email">
                        <mat-label>Email</mat-label>
                        <input matInput formControlName="email" />
                    </mat-form-field>
                    <button mat-raised-button class="validateEmail">Validate email</button>
                    <mat-divider></mat-divider>
                    <mat-form-field appearance="fill" class="fname">
                        <mat-label>First Name</mat-label>
                        <input matInput formControlName="fname" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="lname">
                        <mat-label>Last Name</mat-label>
                        <input matInput formControlName="lname" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="phone">
                        <mat-label>Phone Number</mat-label>
                        <input matInput formControlName="phone" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="companyName">
                        <mat-label>Company Name</mat-label>
                        <input matInput formControlName="companyName" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="title">
                        <mat-label>Title</mat-label>
                        <input matInput formControlName="title" />
                    </mat-form-field>
                </form>
            </div>
        </div>

Answer №1

Your HTML code seems to be in good shape, but if you're encountering issues with filling data into form controls, here's how you can tackle it:

constructor(private fb: FormBuilder) { }

fillUpData() {
     this.generalForm = this.fb.group({
         email: [this.data.email, [Validators.required]],
         fname: [this.data.fname, [Validators.required]],
         lname: [this.data.lname, [Validators.required]],
         phone: this.data.phone,
         companyName: this.data.companyName,
         title: this.data.title
    });
}

You should invoke this method once you have the necessary data. This usually happens after making an API call.

getUserGeneralDetails() {
    this.isInProgress = true;
    this._userProfileService
      .getUserGeneralDetails(this.userId)
      .pipe(finalize(() => (this.isInProgress = false)))
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.data = res.data;   // Once you receive the data, call the function.
            this.fillUpData();
          }
        },
        error: (err) => this._notificationService.showError(err),
        complete: noop,
      });
  }

If you encounter a form group-related error after following these steps, consider adding a condition like *ngIf="generalForm" in your HTML code. This will ensure that the formControl is only rendered when the form exists.

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

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

Is there a way to make a text area move along with the mouse cursor?

I have been working on my first website and everything is running smoothly so far. However, I have a new idea that I am struggling to implement. Some of the pages on my site feature a video player with buttons to select different videos. When a viewer hove ...

Key to Perform Right Click

Hey, I could use a little advice window.addEventListener('keyup', function (event) { if (document.activeElement && document.activeElement.tagName === 'INPUT') { return; } switch (String.fromCharCode(event.keyCode ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

I have decided to integrate Laravel with Vite for building CSS and JS. However, when I attempted to run `npm run dev`, it appeared to execute but was accompanied by an error in the background that

Hi there, I'm new to Laravel and I've created a small app that primarily uses CSS and JS scripts. Everything was working fine in my development environment, so I decided to push it to a production server. However, after installation, my code does ...

What is the method to create a resizable table column border rather than resizing the bottom corner border?

At the moment, we are able to resize the table border when we drag the corner. However, my goal is to enable resizing on the right side of the full border. https://i.sstatic.net/yFI24.png Below is the CSS code for resizing: th{ resize: horizontal; ove ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Using AngularJS to handle error validation for dropdowns and select elements that will redirect using the ng

Currently, I am utilizing angularjs's ng-href along with a select HTML element containing ng-model. The ng-href is being used to link to the "selectedItem" from ng-model. However, I have encountered difficulty in validating or displaying an error mess ...

How can I restrict input to only numbers and one decimal point using JavaScript?

The following code I have is not functioning as expected: function validateInputValue(element) { var regex = /\D$/i; // Important: avoid white spaces in password if(regex.test(element.value)) { alert("Please check your input format"); e ...

My discord.js bot remains silent in response to a user's message, even when no errors are present

My Discord bot is using version 13.1.0 of discord.js and my Node version is 16.7.0. I utilized the commands npm init to generate a package.json file and npm install discord.js to install the Discord package. The code for the bot is written in index.js, an ...

Localizing in Angular 2 does not retrieve locale information

@robisim74 Hello, I've been working on integrating Angular2localization into my new Ionic 2 (rc0) application. My goal is to translate messages and format dates, numbers, percentages, and currency amounts. One issue I've encountered is that whe ...

Struggling with importing modules from peer libraries within an Angular monorepo

Background We are currently working with a monorepo Angular UI component library and attempting to implement Lerna 6. The Challenge We encountered a compilation failure while trying to build one of the libraries that relies on a peer library within the ...

JavaScript array as a reliable data storage solution

This is my unique jsp code where I am attempting to push certain data into a JavaScript array. <% int proListSize = proList.size(); ProfileDAO proDAO = null; for(int i = 0, j=1; i < proListSize; i++){ proDAO = ( ...

Difficulty Resolving Parameter Resolution in Angular 5 Shared Library Module ([object Object], ?, ?)

I'm facing an issue while attempting to integrate a custom shared component library into my Angular application, which has been upgraded from Angular 5 to Angular 4. Unfortunately, I am unable to resolve the problem at hand. The error message I&apos ...

Is it possible to install in a directory other than the one specified in package.json

I have organized my folders exactly how I want them to be. In one specific folder, all of my configuration files reside (most importantly package.json). I am looking to install this package.json configuration in a different path, specifically c\instal ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

Top method for creating 12 dynamic product pages using AngularJS with customized routing and templates

As someone who is still relatively new to AngularJS, I am looking for advice on how to properly structure the products section of my application. My main product page will display all 12 products with clickable links to individual product pages. Each indi ...

Retrieving Values Entered by Users in a Bootstrap Form

Here is the code I have for an input field within Bootstrap: <div class="form-group"> <label for="f2">F</label> <input type="text" class="form-control" name="f2" id="f2&quo ...