Troubleshooting: Why is my Angular Ionic Reactive Form not showing up on the

I'm currently experiencing an issue with my Angular/Ionic form, where the form controls are not displaying correctly on the web. My goal is to create a dynamic form that allows users to input the number of groups and students for each year. However, when I view the form in the browser, I can only see the "Submit" button, but none of the form fields are visible.

Below is the code I am working with:

<form [formGroup]="inputForm" (ngSubmit)="onSubmit()">
  <ion-list formArrayName="years">
    <ion-item-group *ngFor="let year of getYearsControls(); let yearIndex = index">
      <ion-header>
        <ion-label>Year {{ yearIndex + 1 }}</ion-label>
      </ion-header>
      <ion-item>
        <ion-label>Number of groups</ion-label>
        <ion-input type="number" formControlName="numGroups" placeholder="Number of groups"></ion-input>
      </ion-item>
      <ion-item *ngFor="let group of getGroupsControls(yearIndex); let groupIndex = index">
        <ion-label>Number of students</ion-label>
        <ion-input type="number" formControlName={{groupIndex}} placeholder="Number of students"></ion-input>
        <ion-button (click)="removeStudents(yearIndex, groupIndex)" color="danger" fill="clear">Remove Students</ion-button>
      </ion-item>
      <ion-item-divider>
        <ion-button (click)="addStudents(yearIndex)" expand="block">Add Number of Students</ion-button>
      </ion-item-divider>
    </ion-item-group>
  </ion-list>
  <ion-button type="submit" expand="block">Submit</ion-button>
</form>

I have created a FormGroup that includes a FormArray for the years, and each year contains a FormArray for groups, along with individual form controls for the number of groups and students.

While I have checked my component logic and template bindings, I am unable to identify why the form controls are not rendering within the Ionic components.

If you have any suggestions or solutions to help me resolve this issue, I would greatly appreciate it. Thank you!

export class TestFormComponent  implements OnInit {
  @Output() formDataSubmitted = new EventEmitter<any>();
  inputForm!: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.inputForm = this.formBuilder.group({
      years: this.formBuilder.array([])
    });
    this.addYearsControls();
    console.log('inputForm initialized:', this.inputForm);
  }

  ngOnInit() {}


  addYearsControls() {
    const yearsFormArray = this.inputForm.get('years') as FormArray;
    for (let i = 0; i < 5; i++) {
      yearsFormArray.push(this.createYearGroup());
    }
  }

  createYearGroup(): FormGroup {
    return this.formBuilder.group({
      numGroups: ['', Validators.required],
      groups: this.formBuilder.array([])
    });
  }

  addStudents(yearIndex: number) {
    const yearGroupsArray = (this.inputForm.get(`years.${yearIndex}.groups`) as FormArray);
    yearGroupsArray.push(this.createGroupControl());
  }

  removeStudents(yearIndex: number, groupIndex: number) {
    const yearGroupsArray = (this.inputForm.get(`years.${yearIndex}.groups`) as FormArray);
    yearGroupsArray.removeAt(groupIndex);
  }

  createGroupControl(): FormControl {
    return new FormControl('');
  }

  onSubmit() {
    this.formDataSubmitted.emit(this.inputForm.value);
    console.log(this.inputForm.value);
  }

  getYearsControls() {
    return ((this.inputForm.get('years') as FormArray).controls);
  }

  getGroupsControls(yearIndex: number) {
    return ((this.inputForm.get(`years.${yearIndex}.groups`) as FormArray).controls);
  }
}

Answer №1

  1. Make sure to include the

    [formGroupName]="yearIndex"
    when looping through the year form groups using getYearsControls().

  2. Don't forget to add the formArrayName="groups" before creating each group FormControl with getGroupsControls(yearIndex).

<form [formGroup]="inputForm" (ngSubmit)="onSubmit()">
  <ion-list formArrayName="years">
    <ion-item-group
      *ngFor="let year of getYearsControls(); let yearIndex = index"
      [formGroupName]="yearIndex"
    >
      <ion-header>
        <ion-label>Year {{ yearIndex + 1 }}</ion-label>
      </ion-header>
      <ion-item>
        <ion-label>Number of groups</ion-label>
        <ion-input
          type="number"
          formControlName="numGroups"
          placeholder="Number of groups"
        ></ion-input>
      </ion-item>
      <ng-container formArrayName="groups">
        <ion-item
          *ngFor="
            let group of getGroupsControls(yearIndex);
            let groupIndex = index
          "
        >
          <ion-label>Number of students</ion-label>
          <ion-input
            type="number"
            formControlName="{{ groupIndex }}"
            placeholder="Number of students"
          ></ion-input>
          <ion-button
            (click)="removeStudents(yearIndex, groupIndex)"
            color="danger"
            fill="clear"
          >
            Remove Students
          </ion-button>
        </ion-item>
        <ion-item-divider>
          <ion-button (click)="addStudents(yearIndex)" expand="block"
            >Add Number of Students</ion-button
          >
        </ion-item-divider>
      </ng-container>
    </ion-item-group>
  </ion-list>
  <ion-button type="submit" expand="block">Submit</ion-button>
</form>

Demo @ StackBlitz

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 it possible to add an element to an array every time a particular function is executed?

Implementing infinite scroll involves using an array called hotels that receives data from the $http.get() method. Now, the goal is to populate a new array named hotelsNew[] with the values from the hotels array, while incrementing the values of m and j. ...

retrieve a shared string from an array when toggled

Regarding the use of SelectionModel for mat-checkbox, a function is called on each click: toggleSelection(row) { this.selection.toggle(row); console.log("Selection"); console.log("this", this.selection.selected); this.selection.selected.f ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

The Dropdown Clear Button in Syncfusion's EJ2

I am currently facing an issue while attempting to incorporate Syncfusion's EJ2 components into an Angular application. I have encountered a roadblock with the DropDownList component, as certain features are not well-documented at this time. I noticed ...

The process of releasing a component created with angular-starter onto npm is now underway

After creating angular components with the Angular Starter Kit from https://github.com/AngularClass/angular-starter, I am looking to package them and deploy them on NPM for easy use in other projects. However, I found the documentation to be lacking in thi ...

Why do selected items in Ionic 3 ion-option not get deselected even after reloading or reinitializing the array

HTML File: <ion-item class="inputpsection" *ngIf="showDeptsec"> <ion-label floating class="fontsize12">Department</ion-label> <ion-select (ionChange)="showDepartmentChosen($event)" multiple="true" formControlName=" ...

What is the best way to reset the current page using angular pagination?

I used a tutorial on the pagination implementation in my Angular application, which can be found at this link For the search functionality, I have two components. The first is the parent component that includes the search parameters and a button to trigge ...

The Typescript object may be null even with its initial value set

1: let a: Record<string, any> | null = {}; 2: a['b'] = 2; Encountered the TS2531: Object is possibly 'null' error on Row 2 despite having an initial value. To address this issue, the code was updated as follows: 1: let a: Record ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

If the container encounters an issue while processing asynchronous ngFor directives

Something unexpected is happening in Angular2 when I use an ngIf container with a list created using ngFor. It seems like the view doesn't display items from the observable array the first time they are added after the ngIf container becomes visible. ...

Issue with Angular 6: Jquery unable to detect element when using *ngIf directive

I'm currently developing an app using Angular 6, and I am facing an issue while trying to add a class using the jquery hover() method. In my navigation menu, I have 5 links, and although they all appear the same, 2 of them have an added *ngIf directiv ...

Once the user logs out, they have the ability to navigate back using the back button. What steps can be taken to address this

route.ts const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'dashboard', canActiva ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

Resolving the name error: Importing definition files from node_modules/@types in Angular

After acquiring this set of definitions from a node_modules/@types file, I encountered an issue trying to import it into my js file. I went ahead and executed npm install @types/p5 before including it in my tsconfig.json as follows: "types": [ "n ...

Error TS2322: Cannot assign a variable of type 'number' to a variable of type 'string'

Encountered an issue with TS2322 error while attempting to compile my Angular application. The error occurs when using a variable [link] that represents the index number. When declaring this variable, I use: @Input() link!: string; This link is used as ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

Ways to access subscription value in Angular without relying on async await

Is there a way to extract the value inside the subscribe in Angular? I am dealing with this code snippet: async trackingInfo(trackingNumber) { const foo = await this.userService .trackOrderStatus(trackingNumber) .subscribe((status) => ...

Testing an asynchronous function in JavaScript can lead to the error message: "Have you neglected to utilize await?"

Here is an example of the code I am working with: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } = respon; myStatus = statusCode ...

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...