How to assign a value to an array within a form in Angular 8

I'm facing an issue with my Angular 8 edit form that utilizes a form array. When I navigate to the page, the form array is not populated with values as expected. Can anyone help me identify and solve this problem?

      ngOnInit(): void {
    // Fetching data from route
    this.courseExam = this.activeRoute.snapshot.data['exams']['exams']['records'];
    this.questions = this.activeRoute.snapshot.data['question']['question']["result"];
    this.questionsOld = this.activeRoute.snapshot.data['question']['question']["result"];
    console.log(this.questions)
    this.createForm();
  }

  createForm(): void {
    // Creating the form group
    this.editQuestionFG = new FormGroup({
      title: new FormControl(this.questions.title, Validators.required),
      courseExamId: new FormControl(this.questions.courseExamId, Validators.required),
      courseOptions: this._formBuilder.array([])
    });
    this.setValue(this.questions.courseOptions);
  }


  createItem(): FormGroup {
    return this._formBuilder.group({
      optionTitle: new FormControl('', Validators.required),
      isCorrect: new FormControl(false, Validators.required)
    });
  }

  setValue(item: Options[]) {
    for (let x of item) {
      this.editQuestionFG.controls['courseOptions'].setValue({
        isCorrect: x.isCorrect,
        optionTitle: x.optionTitle
      })

    }
  }

html :

<div class="answer col-lg-12 kt-margin-bottom-20-mobile">
                    <div formArrayName="courseOptions" class="row m-auto"
                        *ngFor="let project of editQuestionFG.get('courseOptions').controls; let i = index">
                        <ng-container [formGroupName]="i">
                            <div class="col-lg-1 kt-margin-bottom-20-mobile icon remove text-center">
                                <label (click)="deleteItem(i)"><i class="la la-trash"></i></label>
                            </div>
                            <div class="col-lg-8 kt-margin-bottom-20-mobile">
                                <mat-form-field class="mat-form-field-fluid" appearance="outline">
                                    <mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
                                    <input matInput formControlName="optionTitle"
                                        [placeholder]="'GENERAL.TITLE' | translate">
                                </mat-form-field>
                            </div>
                            <div class="col-lg-3 kt-margin-bottom-20-mobile icon">
                                <mat-radio-group name="radp" aria-label="Select an option"
                                    formControlName="isCorrect">
                                    <mat-radio-button value='true'>صحیح</mat-radio-button>
                                </mat-radio-group>
                            </div>
                        </ng-container>

                    </div>
                    <div class="add-Item">
                        <button (click)="AddItems()" mat-raised-button type="button"
                            color="accent">{{'COURSE_QUESTION.ADD_NEW_OPTION' |translate}}</button>
                    </div>
                </div>

Still struggling with this issue. Any insights on how I can resolve it would be greatly appreciated.

Answer №1

Here is an alternative approach to consider:

 updateValues(items: Options[]) {
    const formArray = new FormArray([]);
    for (let item of items) {
      formArray.push(this._formBuilder.group({
        correctAnswer: item.correctAnswer,
        answerText: item.answerText
      }));
    }
    this.editQuestionFG.setControl('choiceOptions', formArray);
  }

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

Looking for guidance on implementing throttle with the .hover() function in jQuery?

Seeking a way to efficiently throttle a hover function using jQuery. Despite various examples, none seem to work as intended. The use of $.throttle doesn't throw errors but ends up halting the animation completely. Here is the code snippet in question ...

Effective ways to replace an image using JavaScript

I am currently working on implementing a show/hide function, but I am encountering an issue with swapping the image (bootstrap class). The show-hide function is functioning properly; however, I am struggling to determine which class is currently displayed. ...

Warning of superfluous escape character when executing 'npm start' on a React application

I have encountered a warning while running my React app using npm start. The warning appears in the terminal and reads as follows: Line 24: Unnecessary escape character: \[no-useless-escape The warning is related to the following code snippet: va ...

Retrieving data from the database without the need to reload the page

Hi there! I have a PHP script that fetches data from a database and I want to display this data within a div element with a "link" class without having to reload the page. Check out the code snippet below: <? include('config.php'); $rs = m ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...

The Select element in Next.js needs to have an accessible name - it must have a title attribute for improved accessibility

Just starting out with Next.js and Typescript. I'm in the process of rebuilding an app using Next.js, but I've hit a roadblock when trying to split pages and components. The error message that keeps popping up is "Select element must have an acce ...

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...

Angular Application Functions Properly on Local Machine, Yet Experiences Issues When Deployed on Azure

I've been making the transition from AngularJS to Angular 2 and beyond. I found a tutorial that helped me set up routing with multiple components using Visual Studio IDE, which worked flawlessly on my local machine: However, when I tried to publish i ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? https://i.sstatic.net/4QpWym.png ...

Using href with IconButtonProps is not supported

I'm facing a challenge in creating a wrapper for the IconButton. I aim to pass components or href props, but unfortunately, I am unable to achieve this by passing the IconButtonProps. Is there a way to accomplish this? function CustomIconButton(props ...

Is it necessary to use Hapi.js on the client side in order to establish a websocket connection using the Hapi.js protocol?

Currently, I am in the process of developing an API using Hapi and requiring WebSocket functionality. After some research, it appears that Nes is the preferred choice to integrate with Hapi for this purpose. Fortunately, Nes simplifies the process signific ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Using Javascript, Google Charts is able to interpret JSON data

I am currently working on integrating Google Charts and populating it with data from an external JSON file that I have generated using PHP's json_encode() function. After some effort, I managed to get Google Charts to display data successfully, but f ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

How can I dynamically reference two template HTML files (one for mobile and one for desktop) within a single component in Angular 6?

Here is the approach I have taken. Organizational structure mobile-view.component.html <p> This content is for mobile view </p> desktop-view.component.html <p> This content is for desktop view </p> mobile.component.ts import ...

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object: obj : TestObject = { name: "test", street: "test" subobj1: { status: warning, time: ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

What are the various undisclosed schema types in A-Frame?

I've been exploring different examples of property types in the official documentation and various Github repositories (though now I can't remember which ones). The latter introduced me to unique properties like "min" and "max" for numbers, as we ...

What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the ...