Storing JSON data in an Angular Reactive Form: A Step-by-Step Guide

Is there a way to save JSON data along with Angular reactive form in the FormControl?

For instance:

JSON received from the server  = [{
ctrlname : controlName1,
type : "Link",
unit:"M"

},{
ctrlname : controlName2,
type : "Date",
unit:"L"

}]

// Creating FormGroup

  let a = new formGroup({
    controlName1 : new FormControl(''),
    controlName2 : new FormControl(''),
    })

I would like to include type, unit properties within the formControl. How can I achieve this while creating form group with formControl?

If I retrieve the value of formControl like this: myFormGroup.controls['controlName1'], how can I also get the unit and type values? What is the method to store unit and type JSON during the creation of formControl?

Answer №1

To tackle this issue, a recommended approach is to store additional data in a ViewModel property and regularly update them as the input values change...

interface IFormData: {
  [controlName: string]: {
    value?: string;
    type?: string;
    unit?: string;
  }
}

@Component(...)
export class YourComponent implements OnInit, OnDestroy {

  control1Subscription: Subscription;
  data: IFormData = {
    controlName1: {},
    controlName2: {},
  };
  form: FormGroup;
  serviceData;

  constructor (
    formBuilder: FormBuilder;
  )

  ngOnInit(): void {
    // Retrieve your service data here. Assuming it's readily available

    this.form = this.formBuilder.group({
      controlName1 : new FormControl(''),
      controlName2 : new FormControl(''),
    });

    // Upon each input value alteration, fetch the related information
    this.control1Subscription = this.form.get('controlName1').valueChanges.subscribe(value => {
        const data = this.serviceData.find(data => data.ctrlname === 'controlName1');
        this.data['controlName1'].value = value;
        this.data['controlName1'].type = data.type;
        this.data['controlName1'].unit = data.unit;
    });
  }

  ngOnDestroy(): void {
    this.control1Subscription.unsubscribe();
  }

}

You can create these subscriptions for input value changes using a loop, replacing the fixed ctrlname values with those from your dataset, adapting to your specific requirements.

Subsequently, when you need to access each set of values by referencing objects through keys, you benefit from constant-time lookup efficiency, enabling swift retrieval.

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

Loop through keys of an object using *ngFor

I have an object structured like this "Stage" : { // -> vaga.stage "ID01" : { // -> stage.code "abeb5220-2003-4b8b-a6d5-853a40ca7d60" : { //candidate "email" : "<a href="/cdn-cgi/l/email-protectio ...

How to Showcase Images in an Ionic 2 App Using HTML Content

This amazing app was built with Ionic 2 technology. It leverages a REST API to retrieve data in JSON format. Interestingly, one of the fields sent from the server is HTML content. <div [innerHTML]="'<p>' + eventMoreDetails.DescriptionHt ...

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...

Adding date restrictions to the main method is necessary for controlling the input and output

I have a function in my react-native package that requires "from" and "to" dates as parameters. I need to implement a rule that ensures the "to" date is always after the "from" date. Where should I insert this requirement in the following code snippe ...

What is the best way to iterate over objects within an array in Ionic version 3?

In my array of objects, each object contains another object. I was able to retrieve the value of the supplier's name using the following loop, but it only retrieves the value from one object. I am looking for a way to obtain the supplier's name f ...

Challenge with Angular date selection component

I am currently utilizing ngbdatepicker in my form. I want to save the date separately and retrieve it as shown below. <input class="form-control ngbfield custom-form-control" required [ngClass]="{'is-invalid':f.touched && birthDay.inv ...

Step-by-step guide on setting up pnpm directly, without the need to first

Here I am, faced with a brand new Windows 10 installation - only VS Code is installed and nothing more: Can pnpm be installed and used without the need for npm? Is this action beneficial or detrimental? Consideration: typescript ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Issue arises when compiling React Redux due to a union type that includes undefined

I am currently in the process of learning how to integrate Redux with React using Typescript. I encountered a compilation error that relates to the type of my store's state, specifically as {posts: PostType[]}. The error message states: Type '{ p ...

Error encountered when an Angular expression is changed after it has already been checked in a dynamically generated component

I am encountering a problem with Angular and the CdkPortal/CdkPortalHost from @angular/cdk. I developed a service that allows me to associate a CdkPortalHost with a specified name and set its Component at any given time. This is how the service is struc ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Angular: Discover the best way to delegate translation tasks to your S3 bucket!

I am currently using ngx-translate for handling translations in my Angular application. Everything is functioning properly when the translation files are stored within the app itself. However, I want to move all of my JSON translation files to an AWS S3 bu ...

Configure the server port for transmitting API requests from Angular to NodeJS during the development phase

I've encountered an issue with my MEAN Stack application. I'm using Angular 6 for the front-end and have set up the users routing and back-end login system successfully tested with Postman. However, whenever I try to use the form, I keep encounte ...

TS2392 error: Implementing multiple constructors in Angular 2 is not permitted

Is there a more efficient way to avoid using multiple constructors in a component? Currently, I am encountering the following error: 'Multiple constructor implementations are not allowed'. questions: any[]; constructor( service: QuestionSignup ...

Leveraging ngOnChanges to determine the display of an overlay based on input alterations

Working with TS/Angular on a web application, I made the decision to refactor some code that handles displaying different overlays. Instead of having separate code for each overlay, I consolidated them into one "master overlay" and created a function withi ...

Animation in Angular stops working once the user logs into the system

After creating an animation that triggers when a social login fails, I encountered an issue where it was working in Chrome but not in Safari initially. However, after some time, the animation started working in Safari as well without me making any changes. ...

Displaying an observable array in Angular 8 using console.log

Having an issue displaying the response from an observable on the console in my Angular project. It seems to be coming back as undefined when retrieved from a service. Even when attempting to loop through the data, I get an error stating that it is not ite ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Using Angular to transfer a function to a directive

Looking to pass the (scroll) method to a directive, I initially had it declared like this: <div class="table-responsive" pyb-fixed-table #container> After modifying it to include the method reference: <div class="table-responsive" (scroll)="onS ...

Issue: The client assertion could not be signed due to the absence of client JWKs for Zitadel and OpenID Client integration

Currently leveraging Zitadel as my Identity Provider, I have set up a project and an API with a key. I am now in the process of acquiring a M2M token using the “JWT bearer token with private key” method, recommended by Zitadel (click here). Utilizing t ...