Angular Mat AutoSuggest - Improving User Experience

I am encountering an issue where I can retrieve the list, but as soon as I input any of my data, I receive an error

ERROR TypeError: Cannot read properties of null (reading 'valueChanges')
. How can I resolve this? I have verified the name of my form array and it seems to be correct. Can anyone provide guidance or solutions?

filteredOptions:any;
options = [];



this.serviceLogForm = this.fb.group({
      id:[0],
      Name:[],
      ArrayForm:this.fb.array([this.CreateArray()])
    })

CreateArray(){
    return this.fb.group({
        item:['']
    })
  }

ngOninit{
this.ArrayForm.get('item').valueChanges.subscribe(response => {
      console.log('data is ', response);
      this.filterData(response);
    })
}

filterData(enterData){
    this.filteredOptions = this.options.filter(item => {
      return item.toLowerCase().indexOf(enterData.toLowerCase()) > -1
    })
  }

getData(){
  this.services.dataList(true).subscribe((response) => {
    this.options = response;
    this.filteredOptions = response;
    console.log(response)
  })
}

Here's my services where I map the items of my list and retrieve the specific data

dataList(isActive: Boolean){
        let params = new HttpParams();
        params = params.append('isActive', String(isActive));
        return this.http.get(this.appsetting.baseURL + 'myList/list',{params})
        .pipe(
          map((response:any) => response.items.map(items =>items['Name']))
        );
      }

Answer №1

Check out the API documentation for FormArray.

An ArrayForm is essentially a FormArray, which is an array.

Therefore, you should have something like this:

(this.ArrayForm.at(0) as FormGroup).get('item').valueChanges

I believe you need to declare it first in ngOnInit(index) in order to call the at()

When your class initializes the serviceLogForm in the ngOnInit method, it will have its complete structure:

this.serviceLogForm = this.fb.group({
    id:[0],
    Name:[],
    ArrayForm:this.fb.array([
        this.fb.group({ item:[''] }) // <--------- index 0 of array
    ])
})

Here's a question to ponder - If you will only ever have one form group in this array, why use a form array?

Answer №2

Your ngOnInit function is throwing an error.

You appear to be missing a variable called ArrayForm in your component.

The specific issue lies in

this.ArrayForm.get('item').valueChanges

The error is caused by this.ArrayForm.get('item') being undefined. You should address this issue.

Answer №3

The control named item is not found in your ArrayForm, causing this.ArrayForm.get('item') to return undefined.

Additionally, there are inconsistencies in variable types and variable naming conventions throughout your code.

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

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Troubleshooting the Angular CLI issue: Module 'ansi-colors' not found

Having issues with my angular project, despite installing the latest version of NodeJs and NPM. When I try to run my project using the ng command, I encounter the following error message: Error: Cannot find module 'ansi-colors' Require stack: - ...

Troubleshoot Issue with Installation of angular2-jwt.js and Provide Solutions for Error Code

I am currently following the installation guidelines to install Respond CMS from Github. My progress has hit a snag while attempting to copy files to the public folder using gulp. and it's the third command in step 2. This brief error message aris ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Creating dynamic Angular child routes with variable initial segment

Recently, I've been working on a new project to set up a blogging system. The next step in my plan is to focus on the admin section, specifically editing posts. My idea for organizing the routes is as follows: /blog - Home page /blog/:slug - Access ...

Prohibit the use of explicit type parameters or limit the union type parameters to enhance the safety of the types

When the getValues() function is called without explicit type parameters, the Typescript code functions correctly. However, calling it with explicit type parameters can result in errors (as seen in invocation getValues<'a' | 'b' | &a ...

Ways to specify certain columns for presentation in Angular Material Table

When retrieving data from a WebApi with 10 columns, I am utilizing Angular Material Grid on the Front-End. user: User; dataSource: UsersDataSource; displayedColumns = ['UserName', 'RoleName', 'ISShared', 'IsDeleted'] ...

Angular - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Establishing a connection between TypeScript and MongoDB

Whenever I try to add the mongo connection to the request, I encounter an error. The error message says: 'Property 'dbClient' does not exist on type 'Request<ParamsDictionary>'. I want the connection to be accessible witho ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...

Bird's home - The nest is unable to sort out its dependencies

My implementation of a CryptoModule is quite straightforward: import { Module } from '@nestjs/common'; import { CryptoService } from './crypto.service'; @Module({ providers: [CryptoService], exports: [CryptoService], }) export cla ...

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...

Why aren't all client perspectives updated when I delete documents from the collection?

Currently, I am utilizing Angular2-meteor which is running on Angular2 Beta 1. Within my simple component, I have: A button to add a document. Once added, the document can be removed by its _id using another button. Additionally, there is a "Remove All" ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...

unanticipated installation issue with published npm package on verdaccio

I am on a mission to create and release a package containing commonly used TypeScript functions on Verdaccio, an npm registry that operates on Docker. After completing the build for my TypeScript package, this is how my project structure looks: https://i ...

I am confused about the term "can only be default-imported using the 'esModuleInterop' flag", could you explain it to me?

I ran into a puzzling error: lib/app.ts:1:8 - error TS1259: Module '"mongoose-sequence"' can only be default-imported using the 'esModuleInterop' flag and it seems to be related to this line of code: import _ from 'mongoose-sequ ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Incorporate OpenLayers 4 into your Angular 5 application

I'd like to integrate OpenLayers 4 into Angular 5 for a project. My main goal is to implement the QuickStart example provided on the official OpenLayers Site. This is what I have accomplished so far: npm install ol --save to download the OpenLayer ...

"Alert: The ToastData is nowhere to be found in

In my previous Angular 5 application, I was using ng2-Toasty for displaying toasts. However, since ng2-Toasty does not support Angular 8, I am now trying to switch to ngx-toastr. Upon implementation, I noticed that ngx-toastr does not have an equivalent o ...