在我的Angular应用程序中,我试图根据以下数组中的一些值显示一个按钮:
public filterList: Array<any> = [
{ 'name': 'Product', 'selected': true },
{ 'name': 'Client', 'selected': true },
{ 'name': 'Received', 'selected': false }
];
如果Product
是selected
,Client
是selected
,并且Received
不是selected
然后我想显示一个按钮。
否则,我想显示一条错误消息。
下面的方法执行此功能,但它是不可扩展的。例如,如果我用另一个项更新filterList
,则在该方法中不会检查它。
我不想对阵列位置进行硬编码,而是想在阵列中循环:
ngOnInit() {
this.checkSelectedFilters();
}
checkSelectedFilters() {
if (this.filterList[0].selected === true
&& this.filterList[1].selected === true
&& this.filterList[2].selected === false) {
console.log('Display button');
} else {
console.log('Display error message');
}
}
有人能告诉我如何更新这个方法,使其满足我的上述要求吗?
注意:当应用程序初始加载时,所有selected
值都是false
&由用户更新
我认为最好的办法是将数组转换为对象并检查tbh。。。
checkSelectedFilters() {
const keyedFilters = this.filterList.reduce((acc, v) => Object.assign(a, {[a.name]: a.selected}), {});
if (keyedFilters.Product && keyedFilters.Client && !keyedFilters.Received) {
// button
} else {
//error
}
}
这是假设这些名称在数组中是唯一的,但IDK如果它们不是唯一的,您将如何处理。
最终,您希望函数映射到*ngIf。
<button type="button" *ngIf="isValidList()">Valid Button</button>
<div *ngIf="!isValidList()">Error</div>
而且,按照你的逻辑,但稍微改变一下,在我看来稍微干净一点:
isValidList() : boolean {
let isValid = this.filterList.filter((f) => f.selected
|| (f.name == this.filterList[0].name && f.select)
|| ( f.name == this.filterList[1].name && f.select)).length == 2;
return isValid;
}
此外,使用名为@bryan60的东西和他的keyedFilters会更干净。
假设新项目的逻辑是也不能选择任何新项目,那么这将在没有更改的情况下工作。
但最终,您的数据并没有描述逻辑。为shouldBeSelected
添加一个属性并与之进行比较会更好。。。