我想在ngFor中循环整个数组,最后显示单个值(满足条件)或显示单个替代值(不满足条件)排除所有其他循环值。我的意思是我不想显示循环中除一个以外的任何其他值。
<div *ngFor="let arr1 of array1">
<div *ngFor="let arr2 of array2>
<input [value]="arr1.id==arr2.id?arr2.quantity:'0'>
</div>
</div>
答案 0 :(得分:2)
相反,我建议您在组件文件中执行此操作:
Public qty: number = 0; // initialize with default value
Public getQty():number {
this.qty = array1.filter((item, key) => { // filter the array1
if(item.id === array2[key].id){ // check if item.id is found in array2
return item; // then return the item from array1.
}
})[0].quantity;
}
ngOnInit(){
this.getQty(); // call it here or wherever it is required.
}
在模板中,您可以使用属性:
<input [value]="qty">
答案 1 :(得分:0)
使用*ngIf
解决此问题:
<div *ngFor="let arr1 of array1">
<div *ngFor="let arr2 of array2>
<input *ngIf="arr1.id==arr2.id" [value]="arr2.quantity">
</div>
</div>
答案 2 :(得分:0)
一种解决方案是转换array1,并使用map添加新属性“ quantity2”
this.array1=this.array1.map(x=>{
let unique=this.array2.find(a=>a.id==x.id);
return
{
...x,
quantity2:unique? unique.quantity:0
}
});
答案 3 :(得分:0)
public Value = '0';
for(let i=0; i<array1.length ;i++){
for(let z=0;z<array2.length; z++){
if(array1[i].id === array2[z].id){
this.Value = arr2[z].quantity;
} else{
this.Value = '0';
}
}
}
<input [value]="Value">