Angular 6 - Looping through Material Table inside Material Expansion Panel

Lushmoney picture Lushmoney · Sep 26, 2018 · Viewed 7.5k times · Source

I have an issue I am kinda lost with. I have material expansion panels, which the header is populated by looping through a variable containing the data that I have, which is an array of objects - within that array of objects, there is a key which the value is the expansion panel header. There is also a key which the value is another array of objects, of which I want to loop through to populate a material table inside of each expansion panel.

Here is what I have so far...

titleGroups.ts:

export const titles = [
    {
        title: 'First Title',
        titleId: 'firstTitle',
        info: [
            { name: 'Info One', code: 'infoOne' },
            { name: 'Info Two', code: 'infoTwo' },
            { name: 'Info Three', code: 'infoThree' },
            { name: 'Info Four', code: 'infoFour' }
        ]
    },
    {
        title: 'Second Title',
        titleId: 'secondTitle',
        info: [
            { name: 'Package', code: 'package' },
            { name: 'Package Two', code: 'packageTwo' } 
        ]
    },
    {
        title: 'Third Title',
        titleId: 'thirdTitle',
        info: [
            { name: 'Widget One', code: 'widgetOne' },
            { name: 'Widget Two', code: 'widgetTwo' },
            { name: 'Widget Three', code: 'widgetThree' },
            { name: 'Widget Four', code: 'widgetFour' }
        ]
    }
]

title.component.ts:

import {Component} from '@angular/core';
import {SelectionModel} from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material';
import {titles} from './titleGroups';

export interface TitleNames {
    name: string;
}

const TITLES: any[] = titles;

let TITLE_NAMES;
for(let i = 0; i < TITLES.length; i++)
    for(let j = 0; j < TITLES[i].info.length; j++)
        TITLE_NAMES = TITLES[i].info;

@Component({
    selector: 'aa-titles',
    templateUrl: './aa-titles.component.html',
    styleUrls: ['./aa-titles.component.scss']
})

export class TitlesComponent {
    displayedColumns: string[] = ['select', 'name'];
    dataSource = new MatTableDataSource<TitleNames>(TITLE_NAMES);
    selection = new SelectionModel<TitleNames>(true, []);
    titleData: any;

    constructor() {
        this.titleData = TITLES;
    }

    isAllSelected() {
        const numSelected = this.selection.selected.length;
        const numRows = this.dataSource.data.length;

        return numSelected === numRows;
    }

    masterToggle() {
        this.isAllSelected() ?
            this.selection.clear() :
            this.dataSource.data.forEach(row => this.selection.select(row));
    }
}

title.component.html:

<mat-accordion multi="true">
    <mat-expansion-panel *ngFor="let item of titleData">
        <mat-expansion-panel-header>{{item.title}}</mat-expansion-panel-header>

        <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
            <!-- Checkbox Column -->
            <ng-container matColumnDef="select">
                <th mat-header-cell *matHeaderCellDef>
                    <mat-checkbox (change)="$event ? masterToggle() : null"
                                  [checked]="selection.hasValue() && isAllSelected()"
                                  [indeterminate]="selection.hasValue() && !isAllSelected()">
                    </mat-checkbox>
                </th>
                <td mat-cell *matCellDef="let row">
                    <mat-checkbox (click)="$event.stopPropagation()"
                                  (change)="$event ? selection.toggle(row) : null"
                                  [checked]="selection.isSelected(row)">
                    </mat-checkbox>
                </td>
            </ng-container>

            <!-- Name Column -->
            <ng-container matColumnDef="name">
                <th mat-header-cell *matHeaderCellDef> Name </th>
                <td mat-cell *matCellDef="let element"> {{element.name}} </td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"
                (click)="selection.toggle(row)">
            </tr>
        </table>
    </mat-expansion-panel>
</mat-accordion>

What is happening is that under each expansion panel, it shows only the data for the last element of titles from titleGroups.ts under each expansion panel.

What I want is for the corresponding expansion panel to display the correct data

First Title expansion panel to display a table showing:

Info One

Info Two

Info Three

Info Four

Second Title expansion panel to display a table showing:

Package

Package Two

And so on. I am lost as to how to do this - any help would be greatly appreciated, thank you!

Answer

Burnee picture Burnee · Sep 26, 2018

You should define separated dataSource-s and selectionModel-s for each table: For example you can define an array like this in the constructor:

this.titlesForIterate = titles.map(item => { 
    // I'm not doing it here, but you can also deep clone the item object first 
    item.dataSource = new MatTableDataSource<WidgetNames>(item.info);
    item.selectionModel = new SelectionModel<TitleNames>(true, []);
    return item;
};

And then use titlesForIterate in the *ngFor of the expansionPanels.

<mat-expansion-panel *ngFor="let item of titlesForIterate">

And then inside each expansionPanel use their own dataSource and selectionModel members for their tables.

<table mat-table [dataSource]="item.dataSource" class="mat-elevation-z8">

    ...
                <mat-checkbox (change)="$event ? masterToggle() : null"
                              [checked]="item.selection.hasValue() && isAllSelected(item)"
                              [indeterminate]="item.selection.hasValue() && !isAllSelected(item)">
                </mat-checkbox>
    ...

note: don't forget to refactor the isAllSelected method to receive the parent object as a parameter.