使用ngFor动态添加组件到页面时保持顺序

时间:2016-09-28 09:42:26

标签: angular angular2-template angular2-components ngfor

在父容器中,我有一个字符串列表。在模板中使用此字符串列表来生成子组件。有点简化,看起来像这样:

组件

export class MyComponent {
    private queries = [];
    private currentQuery: string = 'SELECT * FROM something';

    runQuery() {
        this.queries.unshift(this.currentQuery);
    }
}

模板

<div>
    <textarea [(ngModel)]="currentQuery"></textarea>
    <a (click)="runQuery()">Click Me</a>
</div>

<div *ngFor="let query of queries">
    <my-child-container [query]=query></my-child-container>
</div>

这很有效,我可以在页面上动态生成我的子组件。但它没有维持我想要的顺序。您会注意到我使用了unshift(),因为我希望新的查询在我的页面布局上显示以上旧查询。尽管使用了unshift(),但旧查询下方会出现新查询。 ngFor似乎忽略了列表的顺序?

为了更清楚地解释一下,这就是新子组件当前出现在页面上的方式:

<div>I'm the 1st query you ran</div>
<div>I'm the 2nd query you ran</div>
<div>I'm the 3rd query you ran</div>

我想要的是:

<div>I'm the 3rd query you ran</div>
<div>I'm the 2nd query you ran</div>
<div>I'm the 1st query you ran</div>

如何让Angular2尊重列表的顺序?或者我采取了错误的方法吗?

0 个答案:

没有答案