The property is accessed prior to being initialized

In my code, I have a class defined as follows :

export class Group {
    id: string;
    name: string = '';
    type: 'local' | 'ldap' = 'local';
    members: number[] = [];

This class is being used in my application.component.ts file like this :

    protected localGroups: Group[];
    protected ldapGroups: Group[];
    protected ldapGroupsState: 'unloaded' | 'loading' | 'loaded' = 'unloaded';
    public filteredList = this.localGroups.slice(); <-- resulting in an error saying "Property localGroups is used before its initialization"

The filteredList variable is utilized in the following way :

    isFiltered(group: any) {
        return this.filteredList.find(item => item.id === group.id);
    }

I am facing difficulty in resolving this issue.

UPDATE :

I aim to implement a search filter within a mat-select using mat-select-filter.

Here is the HTML section related to this functionality :

                        <mat-select-filter [array]="localGroups" (filteredReturn)="filteredList=$event"
                            [displayMember]="'name'">
                        </mat-select-filter>
                        <mat-optgroup label="Local">
                            <mat-option id="application-local-groups-{{group.id}}" *ngFor="let group of localGroups"
                                [value]="group" [class.hide]="!isFiltered(group)">{{ group.name }}</mat-option>
                        </mat-optgroup>

If I initialize my variables according to Michael D's suggestion, my localGroups list disappears. I need to first conduct a search operation in order to display my local groups.

Answer №1

The issue you're encountering is quite clear.
You are attempting to access the property this.localGroups without initializing it first.
There are a couple of ways to address this problem. One approach would involve making changes to your application.component.ts file by including the following code snippet:

    protected localGroups: Group[] = []; // <-- Modified here
    protected ldapGroups: Group[] = []; // <-- Modification made here as well
    protected ldapGroupsState: 'unloaded' | 'loading' | 'loaded' = 'unloaded';
    public filteredList = this.localGroups.slice();

Alternatively, another solution would be to verify if the property is null before proceeding:

public filteredList = this.localGroups?.slice() // <-- Note the '?' symbol for checking nullness

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

Utilizing Nativescript Angular, personalize the styling by separating the SCSS file into two distinct platform-specific SCSS files labeled as .android.scss and .ios

After modifying my component to convert it into a nativescript angular platform specific SCSS, everything seems to be working fine. The button's background turns yellow on the android platform/simulator and green on IOS, as specified in the SCSS files ...

Issue with Angular 6.1.0: Scroll position restoration feature malfunctioning

RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }) In the latest version 6.1.0, there is a new feature that aims to restore the scroll position after navigation. Unfortunately, I encountered an issue where the scroll restorat ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

Safari experiencing issues with video player controls not functioning properly

Within my application, there is a div element that contains a video. Clicking on the div triggers an event that navigates to another page. Expectation I expect to be able to play the video and use its controls without triggering the navigation event. Ac ...

What is the proper way to apply a background color to the entire body using CSS?

I'm facing an issue with getting the background color to cover the entire body of my webpage. Currently, it only captures a certain size and when there is scrolling on the window, two shades of colors appear. I want the background color to span the en ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Error message for invalid form control not displayed when value is assigned to form control in Angular

I am currently working with this editor: <div id="editor"></div> which sets its value to a form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)` <div *ngIf="FrmGroup.get('name').inv ...

TypeScript: Retrieve the data type of the provided object

Is there a way to create a function that receives a callback and returns the object returned by that callback? Here's an example of what I'm trying to achieve: const my_object = my_function<A extends string, B extends boolean> ("my_o ...

When utilizing custom ngDoBootstrap and createCustomElement in Angular, the router fails to recognize the URL being used

WHEN I implement a custom ngDoBootstrap function instead of the default bootstrap: [AppComponent] like shown below: @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, HelloComponent ], exports: ...

Exploring MongoDB files easily using Angular

I am currently working on implementing a user search feature using Angular to query users from a MongoDB collection. The function on the server side is already operational and functioning correctly with Postman. However, I encountered an error on the clien ...

What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA. item.component.html: <label>items list: <select formControlName="itemsCtl" (change)="onChange()"> <option *ngFor="let item of itemList" [value]="item">{{i ...

Having difficulty obtaining a delegation token through Auth0

I am currently working on an Angular2 application and I have integrated Auth0 for authentication. I successfully set up my Auth0 service by following the example provided here. However, I am facing an issue with obtaining a delegation token from Auth0 to ...

Insert a new item into a current array using Typescript and Angular

-This is my curated list- export const FORMULARLIST: formular[] = [ { id: 1, name: 'Jane Doe', mobileNumber: 987654, secondMobileNumber: 456789, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1bcc0d9ec ...

Guide on combining two classes as the base class for an extended class in Typescript

Is it possible to create a higher order function (HOF) that modifies or adds a property to the prototype of a given class? interface IStore { new (): {}; } interface IWatchable { new() : { watch: boolean; }; } const Store = <T extends ISt ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Trigger an event when an Angular template's *ngIf condition is met

Let's say I am using the Angular directive *ngIf to display a user object like so: <div *ngIf="user$ | async as user" class="container"> <p>{{user.name}}</p> </div> Is there a method where I can trigger some code once this ...

Altering the background color of an individual mat-card component in an Angular application

Here is the representation of my mat-card list in my Angular application: <div [ngClass]="verticalResultsBarStyle"> <div class="innerDiv"> <mat-card [ngClass]="barStyle" *ngFor="let card of obs | async | paginate: { id: 'paginato ...

Encountered a MongoDB error: $pushAll modifier is unrecognized when trying to update a model using Mongoid, Angular, and Rails frameworks

My stack includes angular-8 on the front-end and Rails(5.2) on backend with Mongoid(6.1). I'm working with a multi-level nested form for my Event model, which utilizes accepts_nested_attributes_for for Ticket that in turn accepts_nested_attributes_fo ...