arj
arj

Reputation: 983

mat-list with "X" close button remove an item from UI

I have implemented mat-list for showing items in the UI.A close(X) button added on the right side of the each item.

enter image description here

Html Code

<mat-list >
        <ng-container *ngFor='let item of jsonData| keyvalue ;'>
          <mat-list-item>
            <h3 matLine class='parent-title'> {{item.key}}</h3>
            <mat-icon>close</mat-icon>
            <div>
              <mat-divider></mat-divider>
            </div>
          </mat-list-item>
          <ng-container *ngFor='let child of $any(item.value)'>
            <ng-container *ngFor='let subChild of child | keyvalue'>
              <ng-container *ngFor='let value of $any(subChild.value)'>
                <mat-list-item>
                  <h3 matLine class='child-title'> {{ value }}</h3>
                  <mat-icon (click)='removeFilter($event, value)'>close</mat-icon>
                </mat-list-item>
              </ng-container>
            </ng-container>
          </ng-container>
        </ng-container>
      </mat-list>

Json data

{
    "Parent1": [
        {
            "Data1": [
                "Item1",
                "Item2"
            ]
        }
    ],
    "Parent2": [
        {
            "Data2": [
                "Item3",
                "Item4"
            ]
        }
    ]
}

How can we remove an item when we click on the close button? Is this functionality is possible with mat-list?

It will be great, if some one give solution.'

Thanks in advance

Upvotes: 0

Views: 1606

Answers (1)

Fabian Strathaus
Fabian Strathaus

Reputation: 3570

In Stackblitz your JSON is restructured, which makes it easier to handle the removal of items.

HTML

<h2>Solution 2</h2>

<mat-list>
  <ng-container *ngFor="let item of formattedJsonData | keyvalue">
    <mat-list-item>
      <h3 matLine>{{ item.key }}</h3>

      <mat-icon>close</mat-icon>
      <div class="parent-mat-divider">
        <mat-divider></mat-divider>
      </div>
    </mat-list-item>

    <ng-container *ngFor="let child of item.value; let i = index">
      <mat-list-item>
        {{ child }}
        <mat-icon (click)="removeItem(item.key, i)">close</mat-icon>
      </mat-list-item>
    </ng-container>
  </ng-container>
</mat-list>

Typescript:

  removeItem(parent: string, index: number ) {
    this.formattedJsonData[parent].splice(index,1 );
  }

Upvotes: 1

Related Questions