Retrieving information stored in a FormBuilder through the HTML

Once I set up a FormBuilder during the onInit Lifecyle:

surveyForm: FormGroup;
ngOnInit(): void {
     this.surveyForm = this.formBuilder.group({
       'surveyTitle': new FormControl(null),
       'surveyDescription': new FormControl(null),
       'questionsDetail': this.formBuilder.array([
         this.formBuilder.group({
           'questionType': new FormControl('mcq'),
           'question': new FormControl(null),
           'choices': this.formBuilder.array([])
         })
       ])
     });
    };

I am struggling to find out how to access the controls of my FormArray

<form [formGroup]="surveyForm">
  <input formControlName = "surveyTitle">
  <textarea formControlName = "surveyQuestion"></textArea><div formArrayName='questionsDetail'>
    <div [FormArrayName]="questionsDetail">
      <div *ngFor="let questionDetail of surveyForm.get('questionsDetail').controls; let i=index">
        <div [FormGroup]="i">
          ...
          <div [FormArrayName]="choices">
            <div *ngFor="let choice of surveyForm.get('questionsDetail').controls.get('choices').controls; let in=index">
              <div [FormGroup]="in">
                ...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>

Can someone demonstrate the correct syntax for accessing data inside a FormGroup that is nested within a FormArray? I am having trouble with the ngFor syntax when working with formBuilder.

Your assistance would be greatly appreciated.

Thank you in advance.

Answer №1

Check out the code snippet below:

<form [formGroup]="surveyForm">
  <input formControlName = "surveyTitle">
  <textarea formControlName = "surveyQuestion"></textArea>
  <div formArrayName='questionsDetail'>
    <div formArrayName="questionsDetail">
      <div *ngFor="let questionDetail of surveyForm.get('questionsDetail')['controls']; let i=index">
        <div [FormGroup]="i">
          ...
          <div formArrayName="choices">
            <div *ngFor="let choice of surveyForm.get('questionsDetail')['controls'][i].get('choices')['controls']; let in=index">
              <div [FormGroup]="in">
                ...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>

It's worth noting that you should use

formArrayName="questionsDetail"
instead of binding to [FormArrayName]. The same goes for choices.

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

While attempting to utilize npm install, I encounter an error on a discord bot stating "msvsVersion is not defined."

Struggling with self-hosting a TypeScript discord bot, the setup process has been a puzzle. It's supposed to generate a build directory with an index.js file, but it's unclear. Installed Visual Studio Build Tools 2017 as required, yet running npm ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

Exploring ViewChild Usage in Angular 8's Inheritance

I've encountered an issue with inheritance and ViewChild in a class where I always seem to get undefined. Let me simplify the problem for better understanding. First, let's look at the parent class: @Component({ selector: 'parent', ...

Can one mimic a TypeScript decorator?

Assuming I have a method decorator like this: class Service { @LogCall() doSomething() { return 1 + 1; } } Is there a way to simulate mocking the @LogCall decorator in unit tests, either by preventing it from being applied or by a ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

What is the best way to set up environments for Google App Engine (GAE

After developing a web app with server and client components, I decided to deploy it to Google Cloud using App Engine. Although the deployment process was successful, the main issue lies in the non-functioning env_variables that are crucial for the applic ...

How to Properly Initialize a Variable for Future Use in a Component?

After initializing my component, certain variables remain unassigned until a later point. I am seeking a way to utilize these variables beyond the initialization process, but I am unsure of how to do so. Below is my attempted code snippet, which throws a ...

Define the static property as an array containing instances of the same type

I created a class called Foo with a static property named instances that holds references to all instances. Then, I have another class called Bar which extends Foo: class Foo { static instances: Foo[]; fooProp = "foo"; constructor() { ...

Testing Angular - using observables that return varying values

I'm currently faced with the challenge of testing a component that subscribes to an observable in a service during its ngOnInit lifecycle hook. The component's behavior is expected to change based on the value received from the observable. To sim ...

What is the reason behind the ability to assign any single parameter function to the type `(val: never) => void` in TypeScript?

Take a look at the code snippet below interface Fn { (val: never): void } const fn1: Fn = () => {} const fn2: Fn = (val: number) => {} const fn3: Fn = (val: { canBeAnyThing: string }) => {} Despite the lack of errors, I find it puzzling. For ...

The file functions/lib/functions/src/index.ts is missing, preventing the deployment of Cloud Functions

Whenever I attempt to deploy my Firebase cloud functions, I encounter the following error. Expected outcome: Successful deployment of functions. Error: Error: An issue occurred while reading functions/package.json: functions/lib/index.js is missing and ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

Exploring ways to retrieve the chosen value from a personalized dropdown menu in React?

I'm currently utilizing styled components along with typescript to retrieve the selected option value of a customized dropdown. However, I am encountering an issue where the value does not update as expected. Interestingly, when I remove the opacity f ...

Unlocking the secrets of retrieving the URL query string in Angular2

I'm struggling to extract the URL query string returned by the security API, resulting in a URL format like this: www.mysite.com/profile#code=xxxx&id_token=xxx. My goal is to retrieve the values of code and id_token. In my ngOnInit() function, I ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Testing an Angular hybrid application resulted in the error message "Unable to access property 'nativeElement' of null."

I'm encountering a problem with a straightforward test: it ('should be able to navigate to add program', fakeAsync(() => { let href = fixture.debugElement.query(By.css('.add-program-btn')); let link = href.nativeElement.get ...

Tips for relocating a switcher button using Ant Design Drawer in a React application

*I'm faced with a challenge in my React project where I need to synchronize the movement of a div (switcher-btn) and an Ant Design Drawer. Whenever the Drawer is opened, I want the switcher-btn to move along with it. Below is the code snippet I'v ...

What is the recommended approach for returning two different types in a TypeScript function?

My API function currently performs a post request and returns an Observable of ModelAResponse, which is an interface I have defined. I now want to modify this function so that it can return an Observable of either ModelAResponse or ModelBResponse based on ...