angular - 重构 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);
}
});
});
}
}
解决方案
推荐阅读
- c# - 带有数据源的 Asp 日历重复标签
- java - 使用 AWS S3 作为监控平台的中间存储层
- javascript - 使用“opacityDecayVelocity”属性配置纸纹
- kubernetes - 从 kubectl logs -f 的大量日志中拖尾几行
- r - 如何设置y轴的小数位?
- google-chrome-extension - 如何在 Chrome 扩展程序中以编程方式关闭 gmail 撰写对话框
- c# - 根据分隔符符号格式化字符串
- python - 我需要在 Python2 中制作一个 EAN-13 号码有效性检查器。我不明白为什么这不起作用
- javascript - HTML, JS, 只获取元素的显示值
- c++ - 双向链表节点插入位置