Angular encountering the "TS2531: Object may be 'null' within object properties" error

Attempting to store form control values in an object for passing into an onSubmit method, encountered an error when assigning the form control values to the object. The error message

TS2531: Object is possibly 'null'
appears when trying to access the filters object properties within the onSubmit() method.

Here's the code snippet:

export class SearchBarComponent implements OnInit {
  filtersForm! : FormGroup;
  
  constructor(private jobService : JobsService) { }
  
  @Output() OutputFilter = new EventEmitter<string>();
  
  filters! : {
    city: string,
    level: string
  }

  ngOnInit(): void {
    this.filtersForm = new FormGroup({
      city: new FormControl('Italy, Roma'),
      level: new FormControl(),
    })
  }

  onSubmit(): void{
    this.filters = {
      city : this.filtersForm.get('city').value,
      level : this.filtersForm.get('level').value
    }
    
    this.OutputFilter.emit(this.filters);
    console.log('Submitted');
  }

}

Having trouble understanding what's causing the issue. Attempted to use both ! and ? operators but haven't been able to pinpoint the problem.

Answer №1

Check out this information from the Angular documentation.

In Angular, you can disable controls on a FormGroup. When a control is disabled, it will not be included in the group's value.

The type of

this.filtersForm.get('city').value
is string|undefined. TypeScript will prompt you to handle the possibly undefined value if strictNullChecks is enabled.

If you need to access the value of disabled controls without worrying about undefined fields, you can use this.filtersForm.getRawValue().

Give this a try:

onSubmit(): void{
    const {city, level} = this.filtersForm.getRawValue();
    this.filters = {
      city,
      level 
    }
    this.OutputFilter.emit(this.filters)
    console.log('Submitted')
  }

Answer №2

In addition to Chellapan's answer, here are a few points to consider:

  • Look at the code itself to understand why the "get" method might return null: Abstract Model (AbstractControl class)

  • Using a string literal to access form properties, regardless of field disablement, can lead to errors and potential non-existent property access within your FormGroup instance.

  • The "get" method returns an AbstractControl because it cannot determine at compile time whether the element being accessed is a FormControl or a FormGroup.

  • Consider using the optional chaining operator for safely accessing potentially null object properties. Here's a resource on optional chaining operator: (MDN)

    This snippet shows how you can use it in your code:

    this.filters = { city : this.filtersForm.get('city').value, level : this.filtersForm.get('level').value }

Don't forget to camelCase your class properties instead of PascalCasing like you did with OutputFilter.

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

Dealing with the endless looping problem in Next.js caused by useEffect

Looking to implement a preloader that spins while the content is loading and disappears once the loading is complete. However, encountering an issue where the site gets stuck on the loading page and keeps loading infinitely. I've tried multiple soluti ...

Learn how to access tag attributes within the ngIf function in Angular 2

considering this structure <a *ngIf="canAccess()" routerLink="/adminUsers">...</a> <a *ngIf="canAccess()" routerLink="/link2">...</a> <a *ngIf="canAccess()" routerLink="/otherlink">...</a> <a *ngIf="canAccess()" rout ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Modifying the value of an element in an array of state variables

I currently have an array of objects stored as a state variable. My goal is to create a function that can modify a specific field within one of the objects. interface IItem{ id: string, selected: boolean } const [array, setArray] = useState<IItem[]&g ...

"Error detected - 'ng' command not identified, and 'npm run' unable to locate package

Every time I attempt to start a new project with Angular, I am faced with the following error: error message Even after adding the angular path to my environment and trying all suggested solutions on various websites, the issue persists. If this is inde ...

Is there a way I can keep my ChartJS constantly updated in real time? Currently, it only seems to update when I zoom in or out

I'm looking to create a dynamic graph that updates every 5 seconds or in real-time. I've managed to get it working when zooming in and out of the page, but not when doing nothing. I know it's possible to achieve this, but I can't seem t ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Multiple keyup events being triggered repeatedly

Currently, I am developing an Angular 4 application. Within my component's HTML, there is a textbox where users can input text. As soon as the user starts typing, I want to trigger an API call to retrieve some data. The current issue I am facing is t ...

Having an empty string in an array used with *ngFor can lead to unusual positioning problems, unlike when the array contains non-empty strings

Check out this live demo to see it in action: https://stackblitz.com/edit/angular-5vwspd You might notice that the first 2 days are positioned strangely on the calendar. I'm currently working on a calendar component, and I am using an array called d ...

Angular Back button event not triggering

I'm attempting to redirect the user to a specific URL when they click the back button in their browser. Here is the code snippet: constructor(private router: Router,private location: PlatformLocation) { let eventUrl = window.sessionSt ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Issue with Angular 8 docker container: module not found despite being installed

I am currently working on an Angular 8 single-page application (SPA). Utilizing a Dockerfile that is managed and executed through a Docker Compose setup. Everything was functioning smoothly for weeks until today when, out of nowhere, the setup stopped wor ...

Since integrating redux-persist, accessing the current state of the redux store has become a challenge

For the past two days, I've been searching for answers to my problem without any luck. It seems like no one else is experiencing the exact issue I'm having, so I must be missing something obvious. Ever since I added redux-persist, I can no longe ...

Typescript Key-Value Pair Dynamic Typing

Can someone please assist me with this task? Here is the API response I received: Week At A Glance: { objA: [{}], objB: [{}] }, records: { Employee Records: [{}], Email Records: [{}], message: "" }, history: { [{}] } Despite my attempts, I am facing dif ...

Personalized FavIcon for Angular

My project is deployed in multiple locations with the same Angular code but different Docker files. I am looking to change the favicon in only one specific place without affecting the others. How can I achieve this? I attempted to use the copy command in ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

npm error - The module './selenium-webdriver/lib/input' cannot be located

After updating my Angular project from version 5 to 7, I encountered numerous vulnerabilities. To address this, I followed the suggested commands in "npm audit" which successfully fixed all the vulnerabilities. However, when attempting to run: ng serve ...

The module 'AnotherModule' in a different file has unexpectedly imported a value 'Module in file'. Make sure to include a @NgModule annotation to resolve this issue

After struggling with this problem for the past four days, I've exhausted all resources on Stack Overflow and Google. Hopefully, someone here can provide some insight. I have two Angular 11 libraries - one core and the other called components. Compone ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...