Utilizing Angular's reactive forms to populate an array field with an array of data

I am currently using Angular 6 along with Reactive form to create a form.

Within the ngOnInit() function, I have set up a form group in the following manner:

this.landingPageForm = this.formBuilder.group({
  title: new FormControl('', [
    Validators.required
  ]),
  images: this.formBuilder.array([])
});

For this form group, my intention is to make the images field a hidden input since the values will be populated by the component, while displaying the title to the user.

I have an array variable that stores URLs of the images.

images: Array = [];

console.log(images);

When I console log the images, I get data in the following format:

[
    "https://example.com/image1.jpg", 
    "https://example.com/image2.jpg", 
    "https://example.com/image3.jpg"
]

In order to assign the value of images to the images input field, I am attempting:

this.landingPageForm.setValue({
    title: this.product.info.title,
    images: this.images || [],
});

However, this is resulting in the following error message:

There are no form controls registered with this array yet. If you're using ngModel,
    you may want to check next tick (e.g. use setTimeout).

I have also tried adding a hidden input field for images like:

<input type="hidden" formControlName="images">
and
<input type="hidden" formControlName="images[]">

Still, the same error persists.

How can I successfully assign the values of the images variable to the array input field?

Answer №1

After reviewing your code snippet, I have identified three key points to address:

  • It appears that you are not properly associating your Form Fields with the corresponding Form Control, as indicated by the error message.
  • There seems to be a missing association with the FormName in your HTML code. It's possible that this line is omitted in the provided snippet.
  • Furthermore, there is no need to instantiate the FormGroup within the NgOnInit() function. Instead, you can simply assign the value directly during the initialization phase.

I suggest utilizing the TypeScript snippet below for better clarity and functionality:

export class FormFieldOverviewExample implements OnInit {
   constructor(private formBuilder: FormBuilder) {}
   images: any[];
   product: any;

   // Assign FormControl to the fields
   landingPageForm = new FormGroup({
       title: new FormControl(''),
       images: new FormControl(''),
   });

   ngOnInit() {
       this.images = [
           "https://example.com/image1.jpg", 
           "https://example.com/image2.jpg", 
           "https://example.com/image3.jpg"
       ];
       this.product = {"info":{"title" : "Product Title"}};
       this.landingPageForm.setValue({
           title: this.product.info.title,
           images: this.images || [],
       });
   }

Additionally, ensure your HTML snippet includes the following code for proper form control binding:

<form [formGroup]="landingPageForm">
<input formControlName="images">
</form>

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

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Using checkboxes to filter a list within a ReactiveForm can result in a rendering issue

I have implemented a dynamic form that contains both regular input fields and checkboxes organized in a list. There is also an input field provided to filter the checkbox list. Surprisingly, I found out that when using the dot (.) character in the search f ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

issues arise with tests following the transition from Angular 9 to Angular 10

Recently, I encountered an issue with my jest-tests after updating Angular from version 9 to 10. These tests were working perfectly fine before the update. Can someone guide me on how to resolve this issue? Below is one of the tests that is causing troubl ...

Testing the combination of Angular units with combineLatest

Recently, I delved into unit testing using the Jest Framework in Angular. However, I've encountered a roadblock while trying to write unit tests for the combineLatest RxJS operator. Check out my component below: Component: public userData; public pro ...

Creating a personalized validation function in Angular to validate a form field against another form field

Below is the TypeScript code for the EtcAddAuthorityComponent: export class EtcAddAuthorityComponent implements OnInit { // Code here... } The HTML code for the component is as follows: <h1 mat-dialog-title>Add Authority</h1> <div mat-di ...

Issues with Angular Material animations may arise following the implementation of a custom theme

Recently, I made the switch to a custom theme in Angular Material version 7 and Angular version 7. Everything seems to be working fine except for the animations - specifically, the mat-progress-bar is no longer moving as expected. This is the code for my ...

The FullCalendar does not appear as expected on Angular version 16

https://i.stack.imgur.com/DTAKr.pngI followed the steps to install FullCalendar in my Ionic 6 Angular 16 app as outlined on https://fullcalendar.io/docs/angular. However, nothing is showing up in the browser (chrome). The Inspector tool shows that the Ful ...

Angular 2 now has the ability to detect keydown events triggered from any part of the page

Is there a way to enable keyboard control for a view? I attempted using document.keydown, but it wasn't successful. How can I make the document accept keyboard input? A solution that worked for me was implementing this in my component class: @HostLi ...

Angular: merging object values into a single string by looping over them

i am dealing with the following data : "commercialRanges": [ { "rangeId": "700", "rangeName": "POSTPAID" }, { "rangeId": "500", "rangeName": "PREPAID" }, ] In my view, I am aiming to display the ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...

The struggle continues in attempting to adjust Angular Material 2 dialog positioning using MdDialogConfig

Does anyone know how to adjust the position of an MdDialog? openDialog() { let config = new MdDialogConfig(); config.height = '15px'; config.position.left = '5px'; let dialogRef = this.dialog.open(BasicAlertDialog, config); dialogRef. ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...

Troubleshooting: Angular 2 router events subscription not triggering

Currently, I am utilizing a breadcrumbs component that subscribes to the router events. However, there is an issue where the subscription does not trigger the first time the component loads. ngOnInit(): void { console.log("oninit beradcumbs"); this.ro ...

Angular TimeTracker for tracking time spent on tasks

I need help creating a timer that starts counting from 0. Unfortunately, when I click the button to start the timer, it doesn't count properly. Can anyone assist me in figuring out why? How can I format this timer to display hours:minutes:seconds li ...

Angular2 displays an error stating that the function start.endsWith is not recognized as a valid function

After switching my base URL from / to window.document.location, I encountered the following error message: TypeError: start.endsWith is not a function Has anyone else experienced this issue with [email protected]? ...

CSS styling is not being applied to buttons within Ionic 2

I'm completely new to Ionic and hybrid apps as a whole. I've been experimenting with a test app, but for some reason, none of the CSS seems to be working. Could someone please help me figure out what mistake I might have made? Here are my files: ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...