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

What is the process for defining a property type as a textual representation of a Type name in TypeScript?

Consider the following classes and interface: class Foo {} interface Bar {} I am looking to define a type that includes a property with a specified type: type DynamicPropertyName<T> = ... <-- ??? After defining the type, I want to use it like th ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

Using [(ngModel)] on a field within an object that is nested inside another object

I am facing a challenge as I attempt something that may or may not be feasible. Within an Angular form, I have an object structured like this: export class NewUserRegisterModelDTO{ userData:UserDetailModelDTO; roles:RoleModelDTO[]; ownerData:O ...

Chai expect() in Typescript to Validate a Specific Type

I've searched through previous posts for an answer, but haven't come across one yet. Here is my query: Currently, I am attempting to test the returned type of a property value in an Object instance using Chai's expect() method in Typescript ...

Facebook is failing to detect meta tags for Angular Universal

I am facing an issue where the meta tags are not showing up on my article pages for Facebook sharing, despite using Angular Universal with Server-side rendering. Although Google Indexing is working fine and the meta tags are visible in the page source, the ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...

Transform angularjs directive into angular 10

After stumbling upon this intriguing code snippet, I decided to integrate it into my angular project: 'use strict'; /** * A mesmerizing floating text animation */ angular.module('g1b.text-animation', []). directive('textAnimatio ...

Firebase Functions Project encountering a "Cannot find module" error in VS Code

While working on a firebase functions project in Visual Studio Code, I encountered an issue inside the index.ts file. The imported modules were not being recognized even though autocomplete showed that the modules exist. When attempting to import them, I k ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...

Challenges with Nested Reactive Form in Angular 4

I am utilizing Angular 4 reactive to develop nested forms. The structure of my forms is as follows: Form Group (userform) FormArray (users) FormGroup (idx) In the complete table, it falls under the Form Group. Each table row is a part of FormArray ...

Having difficulty deploying a Node.js and Angular app on an Azure Web App via Azure DevOps

I am currently working on setting up a pipeline for my MEAN stack application in Azure DevOps. The frontend is developed using Node.js with Angular, while the backend is built with Node.js and Express. 1) Once I deploy the frontend Node.js project to an A ...

Reducing file size when uploading images in Angular4 through image compression

saveImage(event: any, type, image_type) { this.uploadImageFlag = true; const fileList: FileList = event.target.files; if (fileList.length > 0) { const file: File = fileList[0] this.files.set('files', file, file.name) ...

The MUI DataGrid's onCellEditStop event triggers when a cell's value is

When using MUI DataGrid, I encountered an issue where the value of a previously edited cell changes when editing another cell. I read that using onCellEditCommit as a solution, but since it's deprecated, I'm seeking an alternative fix. const ha ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Different Types of Props for Custom Input Components using React Hook Form

Struggling with creating a custom FormInput component using React Hook Form and defining types for it. When calling my component, I want to maintain autocompletion on the name property like this ... <FormInput control={control} name={"name"}& ...

Sending information from a component inside a router-outlet to a higher-level "Parent" component in Angular 2

Is there a way to transfer data from a component embedded within a router-outlet tag in a "parent" component's HTML template back to the parent component? ...

Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet: export function buildRoutes(options: any, router: Router, roles: string[]): Routes { const lazyRoutes: Routes = Object.keys(options) ...

Informing the observer once the request has been completed is my goal, in order to cease the display of the loading spinner

When I intercept requests using an interceptor and inject the LoadIndicatorService I created, everything works smoothly. However, when I load users inside ngOnInit, the LoadIndicator treats the request as on-the-fly. Below is the code snippet: @Inject ...

The dynamic duo: Formik meets Material-UI

Trying to implement Formik with Material-UI text field in the following code: import TextField from '@material-ui/core/TextField'; import { Field, FieldProps, Form, Formik, FormikErrors, FormikProps } from 'formik'; import ...