Angular2 模板 html 循环数组到 return true of false
Angular2 template html loop array to return true of false
示例:
我有以下对象:
{
"Person": {
"Name": {},
"Hobbies": {
"0": {
"Description:Soccer": {},
"IsActive:false": {}
},
"1": {
"Description:Hockey": {},
"IsActive:false": {}
},
"2": {
"Description:Tennis": {},
"IsActive:true": {}
}
}
}
}
我想遍历数组并检查是否有任何爱好处于活动状态。
如果是这样,它应该 return 为真,并显示图像。
<img [src]="Person.Hobbies != null ? './images/hobby.png' : ''"/>
我希望图片只显示一次。
可以使用 html 吗?
您可以使用 ngFor 循环,以在数组中显示所有内容。
<img [src]='./images/hobby.png' *ngFor="let hobby in Person.Hobbies"> </img >
如果出于任何特定原因您只想显示一个子集,则为列表中的每个爱好添加一个 ngIf 条件。
示例
<div *ngFor="let hobby in Person.Hobbies">
<img *ngIf="hobby.IsActive" [src]='./images/hobby.png'>
</div>
我会在你的组件中设置一个属性
<img *ngIf="showHobbyImg">
this.showHobbyImg = false;
const hobbies = this.person.Person.Hobbies;
for (key in hobbies) {
if (hobbies["IsActive:true"]) {
this.showHobbyImg = true;
break;
}
}
如果您使用的是 lodash,您可以稍微简化一下:
this.showHobbyImg = _.some(this.person.Person.Hobbies, ['IsActive:true', {}]);
示例:
我有以下对象:
{
"Person": {
"Name": {},
"Hobbies": {
"0": {
"Description:Soccer": {},
"IsActive:false": {}
},
"1": {
"Description:Hockey": {},
"IsActive:false": {}
},
"2": {
"Description:Tennis": {},
"IsActive:true": {}
}
}
}
}
我想遍历数组并检查是否有任何爱好处于活动状态。 如果是这样,它应该 return 为真,并显示图像。
<img [src]="Person.Hobbies != null ? './images/hobby.png' : ''"/>
我希望图片只显示一次。
可以使用 html 吗?
您可以使用 ngFor 循环,以在数组中显示所有内容。
<img [src]='./images/hobby.png' *ngFor="let hobby in Person.Hobbies"> </img >
如果出于任何特定原因您只想显示一个子集,则为列表中的每个爱好添加一个 ngIf 条件。
示例
<div *ngFor="let hobby in Person.Hobbies">
<img *ngIf="hobby.IsActive" [src]='./images/hobby.png'>
</div>
我会在你的组件中设置一个属性
<img *ngIf="showHobbyImg">
this.showHobbyImg = false;
const hobbies = this.person.Person.Hobbies;
for (key in hobbies) {
if (hobbies["IsActive:true"]) {
this.showHobbyImg = true;
break;
}
}
如果您使用的是 lodash,您可以稍微简化一下:
this.showHobbyImg = _.some(this.person.Person.Hobbies, ['IsActive:true', {}]);