An issue arises following an upgrade in Angular from version 9 to version 10, where the property 'propertyName' is being utilized before it has been initialized

I've spent time looking on Google, Github, and Stackoverflow for a solution to this error, but I'm still struggling to fix it. Can anyone offer a suggestion or help?

Recently, I upgraded my Angular project from version 9 to version 10, and after the update, I started encountering errors like the ones below in a couple of modules.

Error: Property 'searchParameters' is being used before its initialization.

Code snippet: address: this.searchParameters?.address,

In short, here's a part of the code:

interface PartnerSearchParameters {
   name?: string;
   code?: string;
   address?: string;
   taxRegNumber?: string;
}

@Component({
  selector: 'app-partner-search-list',
  templateUrl: './partner-search-list.component.html',
  styleUrls: ['./partner-search-list.component.scss']
})

export class PartnerSearchListComponent implements OnInit, AfterViewInit {

searchParameters: PartnerSearchParameters;

modelMainFilters = {
    address: this.searchParameters?.address,
    code: this.searchParameters?.code,
    name: this.searchParameters?.name 
    taxRegNumber: this.searchParameters?.taxRegNumber ,
  };

constructor(...){}
ngOnInit(): void {...}
...
}

The searchParameters are declared before modelMainFilters, where they are needed. I'm unsure about where the correct place to initialize them would be. Any ideas?

Answer №1

The issue is quite evident here, the properties of searchParameters are being utilized before they are initialized.

An effective solution would be to set it up with default values

searchParameters: PartnerSearchParameters = {
  name: '',
  code: '',
  address: '',
  taxRegNumber: ''
}

Alternatively, consider initializing the modelMainFilters only after the searchParameters have been properly initialized

export class PartnerSearchListComponent implements OnInit, AfterViewInit {
  searchParameters: PartnerSearchParameters;
  modelMainFilters: PartnerSearchParameters;

  ngOnInit(): {
    this.someFunc().subscribe(res => {       // <-- example
      this.searchParameters = res;
      this.modelMainFilters = this.searchParameters;
    });
  }
}

Answer №2

If you want to utilize the non-null assertion operator, you can do so in the following manner:

export interface PartnerSearchParameters {
   name?: string;
   code?: string;
   address?: string;
   taxRegNumber?: string;
}

@Component({
  selector: 'app-partner-search-list',
  templateUrl: './partner-search-list.component.html',
  styleUrls: ['./partner-search-list.component.scss']
})

export class PartnerSearchListComponent implements OnInit, AfterViewInit {

searchParameters!: PartnerSearchParameters;

modelMainFilters = {
    address: this.searchParameters?.address,
    code: this.searchParameters?.code,
    name: this.searchParameters?.name, 
    taxRegNumber: this.searchParameters?.taxRegNumber
  };

constructor(...){}
ngOnInit(): void {...}
...
}

Just remember that using this approach will result in all properties of modelMainFilters being set to undefined, as shown below:

modelMainFilters: {
  address: undefined,
  code: undefined,
  name: undefined,
  taxRegNumber: undefined
}

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

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

Customize the width of the intl-tel-input field using Angular

Utilizing the Nebular ngx-admin template in my Angular application, along with ng2-tel-input for mobile number input. Below is the HTML code I am using: <div class="form-control-group"> <label class="label" for=" ...

Windows drive letter casing error when using Yarn and NextJS

Today, I set up a fresh project using Yarn and NextJS on my Windows computer. When I try to start the project, I encounter an error stating that the casing is "invalid" for the project directory. The specific errors I am facing are: Invalid casing detecte ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

Oops! It seems like there is an issue with the Renderer2 provider in Angular v 4.1.3

Currently in the process of refactoring one of my services due to a breakage post-upgrade. I had to replace browserdomadapter(); along with several other deprecated methods. As a result of multiple deprecations starting around version 2.1 and various brea ...

Exploring the differences between Angular's @Input and @Output directives and utilizing Injectable Services

When considering the differences between @Input/@Output in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()), I find myself questioning whether there are any distinctions beyond the ...

Maximizing Performance of JSON.stringify in Angular

In my Angular app, I have a service that retrieves JSON data from an API. At times, this API sends back over 400 records (JSON Objects). When I directly access the endpoint in my browser, it takes around 5 seconds to load all the JSON data onto the page. ...

Attempting to incorporate an npm package (specifically Howler) into an Angular 2 application

I'm facing an issue with importing Howler into my Angular 2 app as it doesn't have a typings file. Despite my efforts in searching for a solution, I haven't been able to find anything helpful. Can someone guide me on how to import "howler" i ...

Creating organized lists in Angular 4 using list separators

I'm struggling to organize a list with dividers between categories to group items accordingly. Each divider should be labeled with the month name, and the items under it should correspond to that specific month. My Goal: - August - item 1 - item ...

Enhance band tooltips in highcharts angular with a personalized touch

I am currently working on customizing the band names in a highcharts graph within an Angular environment. The code snippet I have included below is intended for this purpose, but unfortunately, it is returning undefined for the band name. You can find the ...

Is it possible to create cloud functions for Firebase using both JavaScript and TypeScript?

For my Firebase project, I have successfully deployed around 4 or 5 functions using JavaScript. However, I now wish to incorporate async-await into 2 of these functions. As such, I am considering converting these specific functions to TypeScript. My conc ...

Resolving the problem of Turkish uppercase dotted i when using the capitalization pipe in Angular 2

I have created a custom capitalization pipe that successfully capitalizes almost all characters, including converting the Turkish 'ı' character into 'I'. However, I am facing an issue where the 'i' character is also being con ...

Choose the initial selection from a list of changing values using Ionic

I'm having trouble selecting the first option in an Ionic select. I've written a condition based on indexes where if the index is 0, checked should be true, but it's still not working. Here is my code: <ion-item> <ion-l ...

What could be causing the presence of a "strike" in my typescript code?

While transitioning my code from JavaScript to TypeScript for the first time, I noticed that some code has been struck out. Can someone explain why this is happening and what it signifies? How should I address this issue? Here's a screenshot as an exa ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

The back-end is not receiving the HTTP Get call, even though the URL is functional in the browser. The error message states that the JSON is

The backend function is functioning properly as both Postman and Swagger are able to call it without any issues. I decided to capture the URL string displayed in the error message and pasted it into a browser. Surprisingly, it successfully reached the bac ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...

Exploring the power of conditional switchMap in Angular2 and enhancing user experience

I am working on a component for creating or editing Trips and I want to use the same form. Is there a way to check in advance if there are any parameters available? ngOnInit() { this.trip = this.fb.group({ id: '', name: ['& ...

After selecting an item, the Next UI navbar menu seems to have trouble closing

Having trouble with the navbar menu component not closing when an option is selected from the menu. The menu does open and close successfully within the menu icon. I attempted to use onPress() but it doesn't seem to be working as expected. "use c ...