如何在ngFor中只显示单个值或单个可选值



我想在ngFor中循环整个数组,并最终显示单个值(在满足条件的情况下(或显示单个替代值

<div *ngFor="let arr1 of array1">                                                
<div *ngFor="let arr2 of array2>                                                                                                              
<input [value]="arr1.id==arr2.id?arr2.quantity:'0'>
</div>   
</div> 

相反,我建议您在组件文件中执行此操作:

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">

使用*ngIf解决此问题:

<div *ngFor="let arr1 of array1">                                                
<div *ngFor="let arr2 of array2>                                                                                                              
<input *ngIf="arr1.id==arr2.id" [value]="arr2.quantity">
</div>   
</div> 

一个解决方案是转换数组1,并使用映射添加新属性"quantity2">

this.array1=this.array1.map(x=>{
let unique=this.array2.find(a=>a.id==x.id);
return
{
...x,
quantity2:unique? unique.quantity:0
}
});

.ts

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';
}
}
}

.html

<input [value]="Value">

最新更新