Tips for resolving the error message: No control can be located using the given path: 'array-> group -> name'

I'm facing an issue with binding my input while using Angular Reactive forms. The forms have been initialized with initial values.

https://i.sstatic.net/ipTRU.png

My HTML structure (using form instead of div) remains the same:

<div [formGroup]="secondFormGroup" class="steper_ctform">

    <div class="steper_sstitle">Add Article</div>

    <mat-form-field appearance="outline" class="steper_artsrh">
        <mat-label>Search Product</mat-label>
        <input matInput placeholder="E.g. 151FGD" class="steper_inp_as">
    </mat-form-field>
    <button (click)="addSfdynamic()">Add Component</button>

    <ng-container formArrayName="articulos">
        <div *ngFor="let art of artarray.controls; let i = index">
            <ng-container [formGroupName]="i">
                <div class="sf_ctart">
                    <div [attr.for]="'art' + i">{{art.value.id}}</div>
                    <div>{{art.value.nart}}</div>
                    <input type="text" formControlName='am'>
                    <button (click)="eraseArt(i)">Delete</button>
                </div>
            </ng-container>

        </div>
    </ng-container>


</div>

This is my TypeScript code:

secondFormGroup = this._formBuilder.group({

  articulos: this._formBuilder.array([
    {
      id:"1",
      nart: "T",
      am: 0,
    },
    {
      id:"2",
      nart: "T",
      am: 1,
    },
    {
      id:"3",
      nart: "M",
      am: 0,
    },      
  ]),

});

public get artarray(): FormArray {
  return this.secondFormGroup.get('articulos') as FormArray
}

I'm struggling to figure out the issue, any help would be greatly appreciated :)

Answer №1

It seems like there might be a better way to initialize values for a FormArray.

One approach could be to create a separate FormGroup for each element in the array, and then add them to the FormArray.

ngOnInit() {
  this.secondFormGroup = this._formBuilder.group({
    articulos: this._formBuilder.array([]),
  });

  this.setArticulosFormGroup([
    {
      id: '1',
      nart: 'T',
      am: 0,
    },
    {
      id: '2',
      nart: 'T',
      am: 1,
    },
    {
      id: '3',
      nart: 'M',
      am: 0,
    },
  ]);
}

setArticulosFormGroup(items: any[]) {
  for (let item of items) {
    let formGroup = this._formBuilder.group({
      id: item.id,
      nart: item.nart,
      am: item.am,
    });

    this.artarray.push(formGroup);
  }
}

Check out the demo on StackBlitz


Further Reading

Learn more about Angular FormArrays here

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

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Issue with MaterialModule in specific modules: Element 'mat-card' is not recognized

I've searched for similar inquiries, yet none appear to address the specific issue I'm encountering. At present, my application incorporates a postModule that is lazy-loaded, while the remaining modules are traditionally loaded. All of them util ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Is there a way to prevent the automatic compilation of all files first when using the --watch option?

I would appreciate it if the tsc --watch option could be modified to only compile files when necessary, similar to how the make utility operates by checking time stamps of .js and .ts files. While not a major issue, I am using TypeScript with a program th ...

Retrieve the component's scope within a function invoked by the [calculateCellValue] method in dxi-column

I am facing a challenge where I am unable to access the context of a component.ts from a function that I call using [calculateCellValue]="function". If I try to pass the context using .bind(this), the interactive features of the DataGrid stop working. The ...

What methods are available to expedite webpack compilation (or decouple it from server restart)?

My current setup includes the following configurations: import path from 'path' import type {Configuration} from 'webpack' const config: Configuration = { mode: 'development', entry: path.join(__dirname, '../..&apos ...

Ways to verify whether a checkbox is selected and store the status in the LocalStorage

Hey there, I'm still new to the world of programming and currently just a junior developer. I have a list of checkboxes and I want to save any unchecked checkbox to my local storage when it's unselected. Below is a snippet of my code but I feel l ...

I'm looking to retrieve the Response from a POST request, which happens to be an array of SearchSample objects in Angular

My Component's Search Function: searchWithNyckel(){ const formData = new FormData(); formData.append('image', this.updateFormGroup.get('updateProduct.image').value); this.productService.searchProductNyckel(formData).subscribe( ...

The file node_modules/@types/node/index.d.ts encountered an error with code TS1084, indicating that the 'reference' directive syntax used is invalid

Having some trouble with typescript compilation. Anyone else encountering this issue? node_modules/@types/node/index.d.ts(20,1): error TS1084: Invalid 'reference' directive syntax. Here is my tsconfig.json setup: { "compileOnSave" ...

Enhancing Password Strength Validation with Formik and Yup in a React Application

I am new to React and currently working on a signup page where I need to validate the password field using Regex. While utilizing Formik and Yup for validations, I encountered an issue where it shows the error that the property being called by the length ...

What are the steps to save information to Firebase's Realtime Database?

Currently, I am facing an issue where user location data is not being written into our Firebase Realtime Database even though the console confirms that the data is fetched correctly every 2 seconds. I am seeking assistance on how to resolve this problem. ...

The module "../../../../@types/parse5" does not have a member named 'DefaultTreeElement' available for export

Encountering an error while trying to develop an angular app: node_modules/@angular/cdk/schematics/utils/html-manipulation.d.ts:9:10 - error TS2305: Module '"../../../../@types/parse5"' has no exported member 'DefaultTreeElement&ap ...

The element is implicitly assigned an 'any' type as the expression of type 'any' cannot be used to index a type with createStyles

My stylesheet looks like this: const badgeStyle = createStyles({ badge: { borderRadius: "12px", padding: "5px 12px", textTransform: "uppercase", fontSize: "10px", fontWeight: 700, lineHeight ...

The element within the iterator is lacking a "key" prop, as indicated by the linter error message in a React component

Encountering an error stating Missing "key" prop for element in iteratoreslintreact/jsx-key {[...Array(10)].map((_) => ( <Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} /> ))} An attempt to resolve this issue was made ...

Encountering a compilation error while attempting to import provideClientHydration

Despite having the Angular-ssr dependencies enabled in my application, I am facing a compilation error while trying to import provideClientHydration from @angular/platform-browser. https://i.sstatic.net/hpsCj.png ...

Tips for extracting subdomains from URLs

Looking for a way to extract only the 'http://abc' part from a URL like http://abc.xyz.com, unfortunately getting the full 'http://abc.xyz.com'. I attempted using: windw.location.origin Do I need to implement an additional method to a ...

The headless Chrome issue arises on continuous integration when the build agent is set up to run as a

My Angular (5) project is set up to run jasmine unit-tests using karma and chrome headless. While it runs smoothly on my local machine, it fails on our VSTS CI server (a Custom Windows 10 VM with node and chrome [69] installed). The build-agent on the VST ...

What could be causing the issue with FindOne not functioning correctly when using TypeORM and MongoDB to find by ID?

Having an issue with typeorm and MongoDB. Attempting to search for a document by Id and encountering unexpected results. When using the syntax const manager = getMongoManager(); const user = await manager.findOne(User, {userId}); I receive an undefined re ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...