Methods for assigning values to a formControl using an array

I have an array of objects and I am attempting to loop through the array, dynamically setting values to a formControl and not displaying anything if the value is null. I have searched for similar solutions but haven't found any references or examples so far.

.html

<form [formGroup]="testForm">
  <div class="class" *ngFor="let item of items">
    <span>{{ item.name }}</span>
    <span>{{ item.email }}</span>
    <div>
      <input type="text" formControlName="number">
    </div>
  </div>
</form>

.ts

testForm: FormGroup;

  items: any[] = [
    {
      name: 'Rob',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ad8e5e8cafeeff9fea4e9e5e7">[email protected]</a>',
      number: 1234
    },
    {
      name: 'Mack',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f426e6c644f7b6a7c7b216c6062">[email protected]</a>',
      number: 9876
    },
    {
      name: 'Mack',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5914383a32192d3c2a2d773a3634">[email protected]</a>',
      number: null
    }
  ];
  get number() {
    return this.testForm.get('number');
  }

  ngOnInit() {
    this.testForm = this.formBuilder.group({
      number: [this.items[0].number, [Validators.required]]
    });
  }

Answer №1

I successfully managed to achieve the desired data display, but it involved a complex process. You're making good progress, but you won't be able to obtain the expected outcome without utilizing a formArray.

For further reference and code demonstration, check out this Stackblitz Link - click here

.html

<form [formGroup]="testform">
  <div *ngFor="let item of itemArray;let i = index" formArrayName="items" >
    <div [formGroupName]="i">
          <span>{{ item.controls.name.value }}</span>
          <span>{{ item.email}}</span>
          <div>
            <input type="text" formControlName="number">
          </div>
    </div> 
  </div>
</form>

.ts

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, FormArray, Validators } from "@angular/forms";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public testform: FormGroup;
    public data: any[] = [
    {
      name: 'Rob',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30625f5270445543441e535f5d">[email protected]</a>',
      number: 1234
    },
    {
      name: 'Mack',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d19cb0b2ba91a5b4a2a5ffb2bebc">[email protected]</a>',
      number: 9876
    },
    {
      name: 'Mack',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="450824262e05312036316b262a28">[email protected]</a>',
      number: null
    }
  ];
  public itemGroup: FormArray;

  constructor(private fb: FormBuilder) {
    const arryOfItemGroup = this.data.map(item => {
      return this.createItemGroup(
        item.name,
        item.email,
        item.number
      );
    });
    this.testform = this.fb.group({
      items: this.fb.array(arryOfItemGroup)
    });
  }

  ngOnInit() {}

  get itemArray() {
    return this.testform.get("items")["controls"] as FormArray;
  }

  private createItemGroup(name, email, number) {
    return this.fb.group({
      name: [name],
      email: [email],
      number: [number]
    });
  }

}

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

Guide for implementing conditional fragment and its value into an anchor HTML tag using Angular 5

I am currently retrieving menus from a service and need to conditionally include a fragment in an anchor tag. The issue I am facing is that when the fragment is empty, it still adds a '#' to the URL which I want to avoid. Take a look at the HTML ...

Node.js Firebase 3.0 authentication integration

After upgrading Firebase to version 3.0 and needing to migrate, I encountered an issue with the authentication of my node server. The code in question is as follows: var firebase = require('firebase'); var config = { apiKey: "<my apiKey> ...

What is preventing Ionic from locating my model interface?

I recently started working with Ionic and I am using a tutorial as a guide to integrate Firebase authentication into my project. However, I am encountering an issue with the user interface that is being generated. When I run ionic serve for the first time ...

Errors with the email composer in Ionic 3 displaying "plugin_not_installed" issue

Currently utilizing this feature within my Ionic 3 application. The plugin has been successfully installed, and the cordova-plugin-email-composer folder is present in the plugins directory. Despite multiple attempts of uninstalling and reinstalling, an err ...

Tips for shifting a fabricjs element generated within a nextjs useState hook?

I encountered an issue where creating a fabric canvas in a useEffect() function prevents me from moving the added images. However, if I create the canvas elsewhere (even though it may be subject to useState asynchrony issues), I am able to move the image ...

Exploring the ideal scenarios for utilizing propTypes in React

When creating in-house components that require specific props to function properly, I believe it is best to conduct prop requirement checks during testing rather than including propTypes in the production code. This is especially important for components t ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

How can one effectively monitor the progress of multiple ajax requests in Angular8 for optimal professionalism?

There is a single completed variable made up of 6 parts, outlined below: selectedCandidateData: Candidate = { candidateBasic: null, experienceList: null, educationList: null, certificationList: null, candidateAbout: null, }; Each part ...

Syntax for the "data" parameter in jQuery.ajax

I am attempting to send the contents of a JavaScript variable to the server for further processing. While I have no issue passing static strings, I encounter a problem when trying to pass a variable containing a string as the WebMethod fails to execute. He ...

Parse the JSON data response as needed in ReactJS

var mydata = [ { source: 11, Registernumber: ">RT-113, <RT-333", jul1: 1004 }, { source: 11, Registernumber: ">RT-113, <RT-333", jul2: 1234 }, // Rest of the data entries... ]; Can we transform the above JSON ...

Present information using Vue.js

Struggling to display just the name from the request object in my form using JavaScript. I'm new to working with JS and need some guidance. I attempted to use {{ request.name }}, but it's not functioning as expected. When I tried {{request}}, it ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Error caused by the shouldDisableDate prop in MUI DatePicker's functionality

<Controller name="toDate" control={control} defaultValue={null} render={({ field }) => ( <DatePicker format="DD/MM/yyyy" value={field.value} onChange={(e) => { setToDate(e); field.onC ...

Get the ID from a row that was created dynamically

I have a webpage that pulls information from my database and displays it. Users should be able to click on the "details" link to see more details about a particular record, or click on an input box in the "check" column and submit to update the record stat ...

Receiving a response from a Node.js server using an AJAX GET request

Here's a snippet of code from app.js that retrieves an aggregated value from mongo.db. I'm attempting to use this response value on my HTML page by making an AJAX call. However, I'm facing an issue where I can't retrieve the value in my ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

Express not invoking Passport LocalStrategy

I added a console.log statement in the LocalStrategy callback of passport.js, but it never seemed to execute. I am using Sequelize for ORM with MySQL. passport.js const LocalStrategy = require('passport-local').Strategy const passport = require( ...

Server-side issue: Ajax POST request returns an empty POST array

I've encountered an issue with my JavaScript function that is supposed to collect data and send it to a PHP file. My problem lies in attempting to submit an array as part of the post: Here's the snippet of the function in question: var string ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...