Angular2搜索数组中的对象

时间:2017-04-04 13:58:32

标签: angular

我有一系列对象,如下所示:

subgoals: any= [
    {'index':'0', 'title': 'Subgoal 1', 'priority': 'Max'},
    {'index':'1', 'title': 'Subgoal 2', 'priority': 'Low'},
    {'index':'2', 'title': 'Subgoal 3', 'priority': 'Avg'},
    {'index':'3', 'title': 'Subgoal 4', 'priority': 'Max'},
]

和两个属性:

title:string='';
priority:string='';

我在模板上迭代这个对象数组:

<div *ngFor=" let chunk of subgoals | chunks: 1; let j = index; " class="mdl-cell mdl-cell--4-col subgoal-card mdl-card">
    <div *ngFor=" let subgoal of chunk | values" >
        <div class="mdl-card__title">
            <h6>{{subgoal.title}}</h6>
        </div>

        <div class="mdl-card__actions">
            <button class="mdl-button" (click)="openSubgoalForEditing(j)">
                View
            </button>
        </div>
    </div>
</div>

<div>{{title}}</div>
<div>{{priority}}</div>

现在,根据我openSubgoalForEditing(j)收到的索引,我想迭代我的subgoals[]数组来获取相应的对象,然后设置我可以在我的模板中显示的标题和优先级。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我应用了一个简单的for循环:

for(let item of this.subgoals){
    if(item.index==index){

        this.title=item.title;
        this.priority=item.priority
    }
}