Using Angular: Accessing a specific object property within a collection for a Form input

Need assistance with handling a collection in an Angular component:

 collection: collectionAbs[];
    
 export interface collectionAbs{
   name: string;
   prop: string;
   secondProp: number;
 }

Initialization:

    this.collection.forEach((item ,index) => {
      formGroup.addControl(index.toString() + "-prop", new FormControl('', [Validators.required])),
      formGroup.addControl(index.toString() + "-secondProp", new FormControl('', [Validators.required]))
    });

The object is set up and now I need to update properties in the form. Here is what I have:

  <div *ngFor="let item of collection; let i = index" >
         <input type="text" name="collection[{{i}}].prop">
         <input type="number" name="collection[{{i}}].secondProp">
  </div>

I'm unsure how to assign these values back to my collection objects. Any better solutions to handle this issue?

@Edit

FormGroup:

 var formGroup: FormGroup;

 formGroup = new FormBuilder().group({
   anotherFormInputOne: new FormControl(null, [Validators.required]),
   anotherFormInputTwo: new FormControl(null, [Validators.required])
 });

Thank you!

Answer №1

Simply implement the following code snippet upon form submission:

    this.collection.forEach((element ,index) => {
      element.property = formGroup.controls[index.toString() + "-property"].value;
      element.additionalProperty = formGroup.controls[index.toString() + "-additionalProperty"].value;
    });

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

Ways to eliminate the excess margin of ng-container from the webpage

When controlling two mat tabs with a statement, I encountered an interesting issue. Both mat-tab elements contain a card-list and are controlled with a statement in ng-container. Strangely, on the first tab, the card has a slight margin from the top when I ...

Utilizing JSON data in Angular 4 to showcase its content on an HTML page

Below is a JSON object that I am working with: { "CandidateSchemaRows": [ { "Description": "sadasd", "Experience": 1, "type": "selectbox" }, { "Description": "erwerw", "Experience": 2, "type": "selectbox" ...

How can I dynamically update content using <router-outlet> on a secondary page?

When accessing my homepage, I want to see a header, footer, and the home-news-page displayed. Additionally, when I click on a link in the header, I would like the content of the home-news-page to change accordingly. Here is how my routing is currently set ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

material-icons appear differently when letter-spacing is applied in iOS browsers

To display levels using star icons from angular material, I wanted the stars to be shown next to each other. I attempted to achieve this by applying letter-spacing: -0.25rem;, but unfortunately it did not render correctly on iOS platforms (resulting in s ...

Creating anonymous TypeScript class factories

Using TypeScript v2.2. In my codebase, there exists a class factory: export class A { name: string; } export function makeConstructor(name: string) { const newClass = class extends A { }; newClass.prototype.name = name; return newClass; } Howev ...

"Utilize a callback function that includes the choice of an additional second

Concern I am seeking a basic function that can receive a callback with either 1 or 2 arguments. If a callback with only 1 argument is provided, the function should automatically generate the second argument internally. If a callback with 2 arguments is s ...

IONIC is displaying an error message indicating that there is no provider available for MapsAPIL

I am trying to implement a search feature with a Google map in my Ionic/Angular project. However, I encountered the following error: Runtime Error No provider for MapsAPILoader! Stack Error: No provider for MapsAPILoader! at inje ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Evaluating a branch using Jasmine Karma

How can I effectively test a branch using Jasmin/Karma within Angular? Consider the following simple function: loadData(){ if(this.faktor){ // here it should be true or false this.callMethod1(); }else{ this.callMethod2(); } } I am ...

transformed an Angular 2 web application into a sleek and functional mobile application

I am looking to convert my basic angular2 web application into a mobile app using cordova. Is there a way to achieve this without relying on Ionic or nativeScript? ...

typescript create a type from a schema

Recently, I received an auto-generated GraphQL schema mapping that looks like this: export const generatedSchema = { query: { __typename: { __type: 'String!' }, account_sample: { __type: '[account_sample!]!', __arg ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Tips for structuring TypeScript with MobX in a ReactJS project

I created a MobX store as shown below. I defined the types of actions in store.js import { action, observable } from 'mobx'; export class SignStore { @observable UserInformation: { email: ''; password: ''; ...

Converting API response in Typescript React to custom internal type with additional properties

I am currently working on a React frontend client using TypeScript. My goal is to send a request to an API endpoint that will provide a list of events. Once I receive the response, I want to map it to an internal type that includes additional properties no ...

Looking for a way to display a spinner loader while transitioning between routes in Angular 4? Although I'm receiving events, I'm struggling to actually show the loader on screen

I'm currently working on a project that requires a loader to display between two routes. Although I am receiving route events, the loader is not visible. import { Component } from '@angular/core'; import { Router, Event, NavigationStart, Na ...

Customize validation timing in Angular Reactive Forms

One common query about the conditional validator is understanding when exactly it gets triggered. Imagine a simple form with just two fields this.form = formBuilder.group({ emailRequired: [false], emailRecipients: [''] }); Now, let's s ...

Utilizing Array Notation in Typescript to Retrieve Elements from Class

In my programming project, I am working with two classes: Candles and Candle. The Candles class includes a property called list, which is an array containing instances of the Candle class. class Candles { public list: Array<Candle>; } class Candl ...

Filtering nested arrays in Angular by cross-referencing with a navigation menu

In the legacy application I'm working on, we have a navigation menu along with a list of user roles. Due to its legacy nature, we have accumulated a significant number of user roles over time. The main goal is to dynamically display the navigation me ...

In order to toggle the input field's state depending on the select component's value in Angular

I have a situation with two components: a select component and an input component, as shown in the image below: https://i.sstatic.net/rjjEn.png Scenario: Currently, the input field is disabled by default. If an option is selected from the select componen ...