【问题标题】:Angular2 search an object in an arrayAngular2在数组中搜索一个对象
【发布时间】:2017-08-29 18:44:16
【问题描述】:

我有一个对象数组,如下所示:

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[] 数组以获取相应的对象,然后设置可以在模板中显示的标题和优先级。

我该怎么做?

【问题讨论】:

标签: angular


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2021-09-03
    • 2017-05-21
    • 2011-04-07
    • 2015-09-12
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多