Assign a value to a FormControl in Angular 6

I have 60 properties linked to 60 controls through the mat-tab in a form. When it comes to editing mode, I need to assign values to all the controls.

One approach is as follows:

this.form.controls['dept'].setValue(selected.id);

This involves locating each control and setting its value individually.

Is there a simpler method, such as:

this.form.setValue(modelName);

Or any other easier way for me to set values without having to write 60 lines of code?

My forms are built using ReactiveForms.

Answer №1

Your approach to handling the model and control relationship may need some adjustments. One method you could try is iterating through the keys of the form controls and setting the values accordingly. Here's an example of how you can do this:

const keys = Object.key(this.form.controls);

keys.forEach((key: string) => {
  this.form.controls[key].setValue(model[key]);
});

If you are creating the controls in a loop, consider setting the values during the creation process.

This resource provided valuable insights on achieving a similar task: https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

Answer №2

To apply the patch value, follow these steps:

const data = {
  name: 'John',
  age: 30
};

this.updateForm.patchValue(data);

Answer №3

If the properties of your model match the attributes of your form (meaning that the model is fully mapped to the form), then you can utilize the setValue method from the Reactive Form.

Your implementation would look like this:

this.form.setValue(yourModelObject)

By doing this, all attributes of your model will be assigned to the corresponding attributes in your form.

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

Can the change listener be used to retrieve the selected option's number in a form-control?

This particular cell renderer is custom-made: drop-down-cell-renderer.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-drop-down-cell-renderer', templateUrl: './drop-down-cell-r ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

Test Transmission Service

Hey there, I'm currently working on writing Angular code for a component that involves an observable. However, I'm facing some issues testing the broadcast service as I keep getting an error indicating that the service is not being called. Does a ...

Ensure to pass the correct type to the useState function

I have a basic app structured like this import React, { useState } from 'react' import AddToList from './components/AddToList' import List from './components/List' export interface IProps{ name: string age: number url: ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

NPM is currently experiencing difficulties installing or uninstalling packages

I'm having trouble installing or uninstalling any npm package because of an error that says "Cannot find module 'emoji-regex'." Does anyone know what might be causing this issue? Here are my configurations. I also tried running "npm install ...

Why is it that when I try to create a table using the "Create Table" statement, I keep getting an error saying "Near '(': syntax error"?

Error : There seems to be a syntax error near "(". Here is the SQL statement causing the issue: CREATE TABLE IF NOT EXISTS tickets ( numero INTEGER PRIMARY KEY AUTOINCREMENT, identifier VARCHAR(4) NOT NULL, subject VARCHAR(150) NOT NULL, ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

The text editor within the NG nickname terminal

After purchasing a new Windows computer, I encountered an issue while attempting to install Angular. The ng commands were not functioning as expected and instead opened a file in the editor. Upon researching a solution at this source, it was suggested tha ...

Karmic Dilemma: Anticipated a single request meeting the criteria but encountered 2 requests

Hello, I am currently working on writing a unit test case for the subscribe method of a controller in Angular. I seem to be encountering an issue with the second test case, as indicated by the following error message: Error: Expected one matching request ...

utilizing $inject method along with supplementary constructor parameters

After referencing the answer found here: Upon implementing the $inject syntax, my controller code appears as follows: class MyCtrl { public static $inject: string[] = ['$scope']; constructor($scope){ // implementation } } // register ...

NGC Error: Unable to locate the type definition file for 'rx/rx.all' - Please fix this issue

Recently, I've been working on some enhancements to the flex-layout project. While running ngc ./node_modules/.bin/ngc -p src/lib/tsconfig.json I encountered an issue... Error Cannot find type definition file for 'rx/rx.all'. It seems li ...

Differences between HTTP requests made from a Node server and an Angular application

A group of aspiring developers is currently working on a cutting-edge web application using Angular 7 with the EAN (Angular Node Express) stack. Our project involves interacting with around 20-25 REST endpoints to retrieve data, perform necessary manipulat ...

Enhancing ag-grid's agRichSelectCellEditor with an arrow for a more user-friendly drop-down experience

The agRichSelectCellEditor currently lacks a visual indicator that it is a drop-down menu. To enhance user understanding, I am interested in including a downward arrow within the cell display. Despite looking through the documentation extensively, I have ...

Exploring Google Places with Angular 2, Typescript, and Ionic 2

Has anyone successfully transformed this code into TypeScript? var map; var infowindow; function initMap() { var pyrmont = {lat: -33.867, lng: 151.195}; map = new google.maps.Map(document.getElementById('map'), { center: py ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

When an object in Typescript is clearly a function, it throws a 'cannot invoke' error

Check out this TypeScript code snippet Take a look here type mutable<A,B> = { mutate: (x : A) => B } type maybeMutable<A,B> = { mutate? : (x : A) => B; } const myFunction = function<A,B>(config : A extends B ? maybeMutab ...

Having trouble locating the 'tsc-watch' module due to the missing 'typescript/bin/tsc' when running the TypeScript compiler

Encountering the error "Cannot find module 'typescript/bin/tsc' when attempting to run tsc-watch yarn tsc-watch --noClear -p tsconfig.json yarn run v1.22.19 $ /Users/jason/Work/VDQ/VDQApp/node_modules/.bin/tsc-watch --noClear -p tsconfig.json Ca ...

Display different icons in an Angular application based on the value received from an API in real

My goal was to create a dynamic form that displays icons for the fields I have created. Here is a snapshot of my UI screen showing the field explorer with the list coming from an API. https://i.sstatic.net/4Ye9G.png I need to place an icon in front of ea ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...