Angular4 * ng如何使用其键名循环嵌套数组

时间:2017-11-13 05:52:35

标签: angular ngfor

我有以下数据样本: sample data

现在我有两个嵌套循环,但我想要做的是,是否可以遍历特定键,例如*ngFor="let key of myArray.functionalArea"

我目前的代码是:

<span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByWorkType of countOfJobsByFields?.workType">
    <li (click)="searchByWorkType(jobByWorkType?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByWorkType.total }}</span></a></li>
 </span>

对于第二把钥匙我有这个:

<span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByFunctionalArea of countOfJobsByFields?.functionalArea">
    <li (click)="searchByFunctionalArea(jobByFunctionalArea?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByFunctionalArea.total }}</span></a></li>
 </span>

注意我不能对两者使用相同的<span *ngFor="let jobByField of countOfJobsByFields">因为它们是我的html中的单独元素。

3 个答案:

答案 0 :(得分:1)

Use following code

 <span *ngFor="let jobByField of countOfJobsByFields">
<div *ngIf='jobByField.workType'>
    <span  *ngFor="let jobByWorkType of jobByField.workType">
        {{jobByWorkType._id}}
    </span>
</div>

<div  *ngIf='jobByField.functionalArea'>
    <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
        {{jobByWorkType._id}}
    </span>
</div>

where JSON:-

countOfJobsByFields = [
      {
        workType: [{'_id':'Part Time', 'total':10}, {'_id': 'Full Time', 'total': 20}]
      },
      {
        functionalArea: [{'_id':'IT', 'total':10}, {'_id': 'Management', 'total': 20}]
      }

    ]

Plunker

答案 1 :(得分:0)

Yes you can :

<span *ngFor="let jobByField of countOfJobsByFields">
    <ng-template *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-template>

    <ng-template *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-template>
</span>

答案 2 :(得分:0)

将以下代码与ng-container一起使用,它将避免与* ngIf一起使用的额外div

<span *ngFor="let jobByField of countOfJobsByFields">
    <ng-container *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-container>

    <ng-container *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-container>
</span>`