How can I retrieve the attributes of a formArray in an HTML document?

Struggling to integrate a reactive Angular form, I'm facing issues accessing the properties of an array in my HTML. This is my first time working with reactive forms and any guidance would be greatly appreciated. Using Angular 10, below is the code snippet:

TS

operationModel: IScriptOperationsModel;
formOperation: FormGroup;

constructor(
  private fb: FormBuilder,
  ...
) {}

ngOnInit() {
  this.operationModel = new IScriptOperationsModel();
  this.operationModel.scriptOperationOrders = [];
  this.buildForm(new IScriptOperationsModel());

  this.scriptOperationsService.findScriptOperation(this.operationId).subscribe((operation) => {
    this.operationModel = operation.data as IScriptOperationsModel;  // api return
    this.buildForm(this.operationModel);  // Passing api response to form
  });
}

buildForm(operation: IScriptOperationsModel) {
  this.formOperation = this.fb.group({
    descriptionCode: [operation.descriptionCode],
    description: [operation.description],
    workStations: this.fb.array([])
  });
  this.formOperation.setControl('workStations', this.fb.array(this.operationModel.scriptOperationOrders));
}

get workStations(): FormArray {
  return this.formOperation.get('workStations') as FormArray;
}

HTML

<div
  class="card"
  [ngClass]="{'bg-principal': idx === 0, 'bg-alternative': idx !== 0}"
  formArrayName="workStations"
  *ngFor="let workstation of workStations.controls; index as idx"
>
  <div class="card-body" [formGroupName]="idx">
    <div class="form-row">
      <div class="form-group col-md-1">
        <label>Id Oper.</label>
        <input
          type="text"
          name="idOperation"
          class="form-control"
          disabled
          formControlName="rank"            <!-- Issue arises here -->
        />
      </div>
      <div class="form-group col-md-2">
        <label>Time</label>
        <input
          type="time" class="form-control" name="defaultTime"
          [formControlName]="defaultTime"   <!-- Issue persists here -->
        />
      </div>
    </div>
  </div>
</div>

Models

export class IScriptOperationsModel extends Serializable {
  public description: string;
  public descriptionCode: string;
  public scriptOperationOrders: IScriptOperationOrdersModel[];     // The array causing issue
}

export class IScriptOperationOrdersModel extends Serializable {
  public rank: number;
  public defaultTime: string;
  public asset?: IAssetModel;
  public provider?: IProviderModel;
}

error-handler.service.ts:87 Error: Cannot find control with path: 'workStations -> 0 -> rank' @ undefined:undefined

NOTE: I have checked various resources such as this, this and this, but none of them provided a solution to my problem!

Answer №1

It appears that the issue lies within this code snippet:

this.formOperation.setControl(
'workStations',
this.fb.array(this.operationModel.scriptOperationOrders) <== here the problem
);

The error is caused by passing an array of IScriptOperationOrdersModel instead of a form group array.
To resolve this issue, you need to iterate through each element in the

this.operationModel.scriptOperationOrders
array, create a new FormControl object for each element, and then add it to the workStations form array.
You can access the elements using controls[indexOfGroup].rate

If you need further clarification, please refer to this example for a better understanding.

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

Sorting files in jquery file upload

Has anyone had experience using the jQuery-File-Upload library from https://github.com/blueimp/jQuery-File-Upload? I'm currently facing an issue and wondering if anyone could assist me in sorting the files in a different manner. By default, this scrip ...

Broaden the scope of a `Record<string, string[]>` by adding a new type of property

When working in Typescript, it appears that defining the type as shown below should create the desired outcome: interface RecordX extends Record<string, string[]> { id: string } However, an error is thrown stating: Property 'id' of t ...

Encountering an issue during deployment in Azure Web App - File package cannot be located

While attempting to pipeline a job and add it to a web app in the Azure portal, I encountered the following error: No package was found with the specified pattern: D:\a\1\s***.zip Please verify if the package mentioned in the task has been ...

What is the best method for updating the .value property within an AngularJS controller?

I managed to successfully pass a value from one AngularJS module to another using the .value method. Here is an example of it working: var app = angular.module('app', []); app.value('movieTitle', 'The Matrix'); var app1 =ang ...

Tips for preserving the contents of a list with HTML and Javascript

My latest project involves creating a website with a To-Do list feature. Users should be able to add and delete items from the list, which I achieved using JavaScript. Now, my next goal is to ensure that the current items on the list are saved when the pag ...

Adjusting the Port Setting in Nuxt 3

After trying the old solution without success, I decided to refer to the Nuxt 3 documentation for answers, only to find that it was not up to date. So, is there a way to change the Nuxt 3 port without modifying the dev script, similar to what @kissu did h ...

What is the proper procedure for invoking a delete method to remove all occurrences of a specific index?

I have implemented a file deletion method in my Ionic 4 App. Using the deleteFile() method, I can successfully delete individual files. However, when attempting to delete multiple files using a forEach loop, the process fails after the first deletion. HTM ...

Alert: It is invalid for an <a> element to be nested inside another <a> element according to validateDOMNesting

I've been experimenting with using react-router in conjunction with reactstrap and create-react-app. While setting up the routing within my application, I encountered a need to utilize state for the reactstrap components. To achieve this, I converted ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

Unable to recreate the Jquery Mobile Autocomplete demonstration

Attempting to recreate a demo using my own remote data source: The HTML page mirrors the demo, with one change: url: "http://localhost/sample.php", Here is the dummy remote data source sample.php <?php $a = array('apple', 'mango&apo ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Exploring unescaped XML for handling unicode characters

Currently tackling the challenge of parsing some XML that is not properly formatted. The XML file contains un-escaped ampersands, which goes against the standard rules for XML files. My goal is to extract unicode formatted phrases from this XML file whil ...

Is it possible to import a custom module after an Angular 2 app has been bootstrapped?

I'm currently in the process of developing a business web application using Angular2 that is based on a web API. But I've encountered a challenge. My goal is to bootstrap my Angular2 app using AuthModule, which is a custom module I have created. ...

utilize optional react useState typings along with JSDoc comments to ensure TypeScript checking for JavaScript code

Utilizing typescript's jsdoc support to type the provided javascript snippet: const [optionalNumber, setOptionalNumber] = useState(null) const handleClick = () => { setOptionalNumber(42) // ^-- Argument of type '42' is not ...

Issues with implementing Jquery datepicker in Django framework

I have thoroughly reviewed almost every question in this feed (at least I like to believe so). However, my jquery datepicker seems to be refusing to cooperate. Despite my best efforts, it has been quite some time since I've been trying to get it to wo ...

What is the best way to implement the populate method in Node.js when working with MongoDB?

Here is the code snippet I am working with: const Order = require('../../models/order'); const Product = require('../../models/product'); Order.find({}, '_id product quantity', function(err, result) { if (result) { con ...

Obtain the cookie and store it in a variable (with a 24-hour expiration) before transferring it to

I am in need of a unique variable that is valid for a single day. This variable should be able to identify the individual website user and remain exclusive to that user. Once obtained, I intend to store this variable in a MySQL column. However, I am facing ...

What could be causing the issue with my Angular integration with Jira Issue Collector to not function properly?

Looking to link the Jira issue collector with an Angular application I attempted something along the lines of Component.ts import { Component, OnInit } from '@angular/core'; import * as jQuery from 'jquery'; declare global { inter ...

Encountered issue with accessing the Error Object in the Error Handling Middleware

Below is the custom error validation code that I have developed : .custom(async (username) => { const user = await UserModel.findOne({ username }) if (user) throw new ConflictError('username already used& ...

Incorporating TWEEN for camera position animations: A complete guide

function adjustCameraPosition(newPosition, animationDuration) { var tween = new TWEEN.Tween( camera.position ) .to( newPosition, animationDuration ) .easing(TWEEN.Easing.Linear.None) .onUpdate(fun ...