Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using

setValue

or

patchValue

However, I am currently encountering a situation where I need to avoid setting the value on each field individually.

Take a look at my form code below:

registrationForm = this._fb.group({
 firstName: ['', Validators.required],
 lastName: [''],
 age: [''],
 country: ['', Validators.required],
 hobby: [''],
 sport: [''],
 status: [''],
 country: ['', Validators.required],
 ...
 ...
});

I have an object named person containing all these properties. To set the values, I am currently doing the following (which works), but I am seeking for a BETTER approach:

registrationForm = this._fb.group({
 firstName: [this.person.firstName, Validators.required],
 lastName: [this.person.lastName],
 age: [this.person.age],
 country: [this.person.country, Validators.required],
 hobby: [this.person.hobby],
 sport: [this.person.sport],
 status: [this.person.status],
 country: [this.person.country, Validators.required],
 ...
 ...
});

Another idea I am considering is creating an object from the person object so that I can utilize either setValue or patchValue methods. Here's a rough concept:

 Object
 .keys(dataObject)
 .map((key) => {
 return { firstName: firstName, lastName: lastName, age: age ...}
 });

If anyone could provide guidance in the right direction, I would greatly appreciate it! Thank you in advance!

Answer №1

If you're confident that the individual object aligns with your form's properties, you can easily update the entire form using setValue by passing in the individual:

this.myFormGroup.setValue(this.individual);

DEMO


UPDATE: In case your individual object has additional properties not present in your form, you can utilize patchValue() instead. This method only updates the matching properties with the form:

this.myFormGroup.patchValue(this.individual);

DEMO

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

Version 4.6.4 of TypeScript is flagging the code as invalid

How can I fix this Typescript problem? const userInformation: { email: string; id: string; _token: string; _tokenExpirationDate: string; } = JSON.parse(localStorage.getItem('userData')); Console Error Message Error: ...

Ways to initiate a language shift in the **JavaScript yearly calendar** when the language is modified in an Angular application

1. I have incorporated ngx-translate into my Angular application for translation purposes. 2. I have successfully implemented the ability to switch languages during initialization by specifying options like {language:'ja'} for Japanese within th ...

To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div. ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

Leveraging the @Input Decorator in Angular 2

Check out the Angular 2 component code sample below @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; c ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

What are the steps to reduce the node version?

How can I downgrade my npm version from 16.13.1 to 12.0.1? Any guidance would be greatly appreciated! Thank you in advance. ...

Use 'data-toggle='button'' in Angular component only once the condition is validated

Looking to verify a certain condition upon clicking, and if it evaluates to true, toggle the element that was clicked <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active" (click)='example ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

Working with JSON data in AngularJS2's templates

Is there a way for me to process JSON from the template in a manner similar to the second code I provided? First code. This method works well when using .json and .map () @Component({ ..// template: `..// <li *ngFor="#user of users"> ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Having trouble writing Jest test cases for a function that returns an Observable Axios response in Nest JS

I'm relatively new to the NestJS + Typescript + RxJs tech stack and I'm attempting to write a unit test case using Jest for one of my functions. However, I'm uncertain if I'm doing it correctly. component.service.ts public fetchCompon ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

There is a Typescript error stating that the argument of type 'NodeListOf<HTMLInputElement> | undefined' cannot be assigned to the parameter of type 'Iterable<HTMLInputElement> ...'

While working on my React/Typescript App, I encountered an issue when trying to access an array of inputs in an event listener using 'e.currentTarget'. To solve this, I utilized Array.from() to convert the NodeListOf into an array and ensured tha ...

Encountering issues with Angular component test cases: receiving a Type Error stating it cannot read the property "contractno" as it is undefined

When attempting to inject the default dependency required to run the spec file without errors, I encountered a Type Error: Cannot read property "contractno" of undefined. /** This is the userModel Class **/ export class UserModel { contractNo: string; ...

Strategies for resolving npm cache errors within an npm package module

Recently, as I was developing an Angular application, I faced some errors. Here's a snippet of the issues encountered: npm ERR! Unexpected end of JSON input while parsing near '...,"karma-qunit":"*","k' npm ERR! A complete log of this run c ...

Concealing the Submit Button During Server Processing (Issues with Binding?)

My Angular 2 form is set up to send data to the server asynchronously. I want to provide users with visual feedback during the waiting period by changing the blue 'submit' button to a greyed-out 'Please wait...' button. To achieve this, ...

Exploring the magic of Angular 4's FormBuilder: creating dynamic FormControls within a

My application enables users to choose from a dropdown menu of events, each with its own unique properties and selectable property values. This is achieved by creating a FormGroup for each event, with a FormControl for each property. Upon initialization, ...