Filtering formArray controls in Angular based on a condition

I'm currently dealing with an issue where I need to filter formArray controls

public checklistForm!: FormGroup;

 this.checklistForm = this.fb.group({
      checklistItems: this.fb.array([])
 });

// some logic

  public checklistItems(): FormArray {
    return this.checklistForm.get('checklistItems') as FormArray;
  }

// filter some checklistsItems
const newFormArray = this.checklistItems().value.filter(// some condition, may be check of id) //this return an array  

HTML

<div *ngFor="let checkList of checklistItems().controls; let checkListIndex=index"></div>

Trying to figure out how to properly filter this checklistItems().controls

Answer №1

In this scenario, utilizing the filter method allows us to save values in a temporary variable that can be employed to execute the *ngFor as demonstrated in the code snippet below. The example showcases filtering form controls based on a search query.

import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import {
  ReactiveFormsModule,
  FormArray,
  FormGroup,
  FormControl,
  FormBuilder,
} from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  template: `
  Search: <input #input (input)="search(input.value)"/>
  <form [formGroup]="checklistForm">
    <div formArrayName="checklistItems">
      <div *ngFor="let checkList of filteredCheckListItems; let checkListIndex=index" [formGroupName]="checkListIndex">
        {{checkListIndex}}
        <input type="text" [formControl]="checkList.controls.test" id="test" name="test"/>
      </div>
    </div>
  </form>
  {{checklistForm.value | json}}
  `,
})
export class App {
  fb = inject(FormBuilder);
  public checklistForm!: FormGroup;
  filteredCheckListItems: Array<any> = [];

  // additional logic

  public checklistItems(): FormArray {
    return this.checklistForm.get('checklistItems') as FormArray;
  }

  ngOnInit() {
    this.checklistForm = this.fb.group({
      checklistItems: this.fb.array([]),
    });
    const checkListItems = this.checklistItems();
    checkListItems.push(this.fb.group({ test: new FormControl('apple') }));
    checkListItems.push(this.fb.group({ test: new FormControl('banana') }));
    checkListItems.push(this.fb.group({ test: new FormControl('grapes') }));

    // store the unfiltered checklist items in the variable
    this.filteredCheckListItems = this.checklistItems().controls;
  }

  search(searchStr: string) {
    console.log(searchStr);
    this.filteredCheckListItems = (<Array<FormGroup>>(
      this.checklistItems().controls
    )).filter((item: FormGroup) => {
      return item?.controls?.['test']?.value?.includes(searchStr);
    });
  }
}

bootstrapApplication(App);

Check out the Stackblitz Demo

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

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

TypeScript - create an Interface that must have either the error field or the payload field, but

My Action type has the following requirements: MUST have a field type {String} CAN include a field payload {Object<string, any>} CAN include a field error {Error} Constraints: IF it contains the field payload THEN it cannot contain the field er ...

Configure NODE_OPTIONS to set the maximum old space size for an Angular application to Nx

In my Angular application within an Nx workspace, I am utilizing the @nx/angular:webpack-browser executor for building. "build": { "executor": "@nx/angular:webpack-browser", ... } This is a sizable application that necessita ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

Issue with Angular Checkbox: Inconsistencies in reflection of changes

I'm encountering a challenge with my Angular application where I have implemented multiple checkboxes within an options form. The issue arises when changes made to the checkboxes are not consistently displayed as expected. Below is the pertinent code ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Customizing the main color scheme in Naive-UI with typescript

I am a beginner with Naive and I want to change the primary color of my app theme to orange. Initially, I used vuestic for this purpose but now I am struggling to implement it. Below is my main.ts file where I had the vuestic override (commented out). Ca ...

Is it possible to create a data structure that enforces specific keys and values types during initialization?

When styling react components with MaterialUI's sx property, I've found that keeping the full style definition inline can lead to cluttered and overwhelming component bodies. To combat this, I've moved all the style definitions into a consta ...

"Encountered an ENOENT error message following the deployment

I'm really hoping for some insight into the current situation. Deploying an Angular 7 / .Net Core 2 application to Azure is giving me trouble. I am utilizing the publish profile provided by Azure in Visual Studio. Everything runs smoothly when testi ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...

Do we really need Renderer2 in Angular?

Angular utilizes the Renderer2 class to manipulate our view, acting as a protective shield between Angular and the DOM, making it possible for us to modify elements without directly interacting with the DOM ourselves. ElementRef provides another way to al ...

Release a new font on npm for integration into your project

In my current web-application project using angular2, I've designed a unique set of music glyphs such as notes, dotted notes, and time signatures. I couldn't find an existing font that suited my needs, so I created this custom font hierarchy: f ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Issue: NG05105 - Unforeseen artificial listener detected @transform.start

Encountered an issue in my Angular 17 app using Angular Material during the execution of ng test: Chrome browser throws 'app-test' title error in the AppComponent with the following message: Error: NG05105: Unexpected synthetic listener @ ...

Import a Component Dynamically Using a Variable in AngularJS

I am attempting to dynamically load a component using a variable, but I keep running into an "Uncaught Error: Template parse errors". How can I achieve this successfully? <app-{{ this.plugin.component }}></app-{{ this.plugin.component }}> ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...

Transitioning to TypeScript: Why won't my function get identified?

I am in the process of transitioning a functional JavaScript project to TypeScript. The project incorporates nightwatch.js Below is my primary test class: declare function require(path: string): any; import * as dotenv from "dotenv"; import signinPage = ...

Proper method for inserting a value into a string array in a React application using TypeScript

How can I properly add elements to a string array in react? I encountered an error message: Type '(string | string[])[]' is not assignable to type 'string[]' You can view the code on this playground link : Here Could it be that I&apos ...

Unselected default option in Angular 4's select dropdown

My goal is to use Angular to retrieve a value from a variable and display it as the first option in a select element, while keeping the rest of the options below static. The issue I am facing is that even though Angular is fetching the data successfully, t ...