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

Best practices for utilizing ngrx/store in Angular 2

As I am refactoring my Angular 2 applications to follow the ngrx pattern, some questions have arisen in my mind: My application retrieves a list of apps and a list of app categories. Can I manage state like "selectedCategory" (where only one can be select ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Improving type checking by extracting constant string values from a union type

I am exploring different types of employees: interface Employee { employeeType: string } interface Manager extends Employee { employeeType: 'MANAGER' // .. etc } interface Developer extends Employee { employeeType: 'DEVELOPER&apos ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

How can we retrieve an API response using Fetch, manipulate it with JSON.stringify(), and what are the next steps in

After countless attempts, I still can't figure out what's missing here. I'm utilizing fetch to retrieve data from Mapbox: var response = fetch(myURL) .then(response => response.json()) .then(data => console.log(JSON.stringify(data))) ...

Searching for a different method in JavaScript that can add items without duplication, as the prependTo function tends to insert multiple items

Every time my code runs successfully, a success message is generated and displayed using prependTo within the HTML. However, the issue arises when the user performs the successful action twice, resulting in two success messages being shown on the screen. ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...

Create a list that starts with a header determined by an object's attribute within an array

Currently in Vue, I am attempting to create a list based on a specific property within an object. The array being retrieved from the vuex store is structured as follows: const array = [ { name: "British title string" nationality: "British" }, { ...

What is the best way to isolate the CSS of individual components in Angular 2?

For the first component: CSS-- ngx-dnd-container { color:black; background-color: white; } HTML- <ngx-dnd-container [model]="targetItemsA" dropZone="multiple-target-a" </ngx-dnd-container> For the sec ...

What is the correct way to establish a Cookie (header) using XMLHttpRequest in JavaScript?

I am attempting to set a cookie in an XSS request using XMLHttpRequest. After reviewing the XMLHttpRequest Specification, I discovered that section 4.6.2-5 indicates that setting certain headers like Cookie and Cookie2 may not be allowed. However, I am lo ...

Adjust the code to enhance the functionality of web components in Sharepoint

I recently came across some code online that I'm trying to modify in order to add an expanding button next to a web part on my Sharepoint site. However, the problem is that by default, all web parts are already expanded and require a click to collapse ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

What is the process for modifying the characteristics of an RMWC Component?

How can I dynamically change the icon attribute in my RMWC Button element when an onClick event occurs? <Button outlined icon={<CircularProgress />} onClick={(e)=> { // e.currentTarget.icon = ''; // console.log(e.c ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

Invoking a function within a functional component from a React element

Let's imagine a scenario where we have a Child component that is a functional component and contains a function called a(): export default function child({ ... }) { ... function a() { ... } ... } Now, let's introduce a parent ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...