leyh
leyh

Reputation: 261

Property is used before its initialization

I have a class like this :

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

I call it in my application.component.ts :

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

My filteredList is used like this :

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

I don't know how to resolve it.

EDIT :

I want to make a search filter inside a mat-select with mat-select-filter.

HTML :

                        <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 like Michael D's answer, my localGroups disappear. I need to do a first research to display my local groups.

Upvotes: 1

Views: 4846

Answers (1)

Just Shadow
Just Shadow

Reputation: 11891

The error you get is self-describing.
You're trying to use property this.localGroups but haven't initialized it anywhere.
You have a few ways to solve the issue. First one would be modifying your application.component.ts to have the following code instead:

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

and the second would be checking for nullness before going forward:
public filteredList = this.localGroups?.slice() // <-- Pay attention to the '?' here

Upvotes: 1

Related Questions