首页 > 解决方案 > 重构 angular mat-selection-list 项删除

问题描述

我正在使用<mat-selection-list>Angular Material UI Framework 中的 a 从列表中添加和删除选项。我不喜欢在我的代码中如何实现这一点,并想询问如何在选定项目和要删除的列表项目之间进行映射。

HTML

    <div id="locationsView">
    <mat-selection-list #locations class="selectionList">
        <mat-list-option *ngFor="let location of locationList">
            {{location}}
        </mat-list-option>
    </mat-selection-list>

    <div class="locationForm" id="addLocationForm" hidden=true>
        <mat-form-field class="inputField">
            <input id="newLocationInput" #newLocation matInput (keyup)="onKeyUp($event, newLocation.value)"
                placeholder="Location">
        </mat-form-field>
        <button mat-icon-button (click)="onClickAddLocation(newLocation.value)" id="addLocation">
            <mat-icon id="add-icon">add_box</mat-icon>
        </button>
    </div>
</div>

<div id="actionFooter">
    <app-actions [locationList]="locationList" [selected]="locations.selectedOptions.selected"></app-actions>
</div>

TS
onClickDelete()方法似乎有效(只要项目的可见文本是唯一的,这对我的用例来说就足够了),但是这段代码让我很难过。必须有一种更精确的方法,使用索引/键将所选项目映射到原始列表...有人可以提供一个不那么令人毛骨悚然的解决方案吗?也许我错过了selectedOptions对象上的一个方法,或者角度框架预见了另一种使用动态列表的方法?

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-actions',
  templateUrl: './actions.component.html',
  styleUrls: ['./actions.component.css']
})
export class ActionsComponent implements OnInit {

  @Input()
  public locationList;

  @Input()
  public selected;

  ngOnInit() {
  }

  onClickDelete() {    
    this.selected.forEach(selectedItem => {

      this.locationList.forEach(listedItem => {

        if (selectedItem._element.nativeElement.children[0].textContent.trim() === listedItem.trim()) {          
          this.locationList.splice(this.locationList.indexOf(listedItem),1);
        }
      });

  });  

  }
}

标签: angularrefactoring

解决方案


推荐阅读