Home > Net >  Angular: Component Iteration: Calls method in wrong component instance
Angular: Component Iteration: Calls method in wrong component instance

Time:11-20

I have a very weird issue. I have the following iteration in my template:

<div class="wrapper">
    <app-group-selector
        (selectedValuesChanged)="updateSelectedGroups(group.name, $event)"
        *ngFor="let group of groups"
        [allValues]="group.allValues"
        [selectedValues]="group.selectedValues"
        class="chart-control-groups-item"
        label="{{ group.name }}"
    ></app-group-selector>
</div>

inside app-group-selector I have this template:

<div class="result-area" [hidden]="!isResultSelectionListOpen">
    <div class="select-all-selector">
        <app-checkbox [inputId]="'select-all'" [(ngModel)]="selectAllItemsCheckbox" [compact]="true" (change)="handleSelectAllCheckbox()"></app-checkbox>
            <label [for]="'select-all'" class="result-label">Select All</label>
        </div>
        <ul class="result-selection-list">
            <li *ngFor="let item of allSelectionItems" class="result-item">
                <app-checkbox [inputId]="item.key" [compact]="true" [(ngModel)]="item.checked" (change)="handleCheckItem()"></app-checkbox>
                <label [for]="item.key" class="result-label">{{ item.key }}</label>
            </li>
        </ul>
</div>

and in the .ts file I have the method:

handleSelectAllCheckbox(): void {
    console.log('all items: '   this.allSelectionItems);
}

Now, in the UI I have 3 app-group-selector components. The strange thing is, that, when I click on the "Select All" checkbox of the last component, it triggers the handleSelectAllCheckbox() method of the first component (I can see that because the console.log shows me the wrong allSelectionItems list.

Now, there should be no connection at all between these components - they should live for their own.

The component is declared in the app.module declarations array as usual.

Can somebody please help me?

CodePudding user response:

[inputId]="'select-all'" is the culprit here. On iteration there will be multiple elements with same id in one document, all the for="select-all" will always refer the first element with that id.

Now you know the solution, you'll have to use dynamic values for id and for like you have done below [inputId]="item.key" and [for]="item.key".

  • Related