当动态添加二级子级时,Angular2 @ ViewChildren / @ViewQuery的QueryList未更新

时间:2016-01-29 13:55:30

标签: angular

我想创建一个目录树,并且无论级别如何都可以访问所有项目,但是当我动态添加二级子项时,@ ViewChildren / @ViewQuery的QueryList不会更新:

import {bootstrap} from 'angular2/platform/browser';
import {Component, View, QueryList,ViewQuery, Query,ViewChildren} from 'angular2/core';


@Component({
    selector: 'item',
})
@View({
    template: `
        <button (click)="addChild()">Add Child</button>
        <ng-content></ng-content>
        <div *ngFor="#child of children; #i = index">
          <item> {{child.name}}</item>
        </div>
    `
})
export class Item {
    //public children = [ { name: 'Child 1', age: 22 } ];
    public children = [];
    addChild() {
        this.children.push({ name: 'Child' + (this.children.length + 1), age: 18 });
    }
}

@Component({
    selector: 'my-app'
})
@View({
    directives: [Item],
    template: `
        <button (click)="addParent()">Add Parent</button>

        <div *ngFor="#user of users; #i = index">
          <item #item> {{user.name}}</item>
        </div>
`
})
export class AppComponent {
    public users = [
        { name: 'Parent 1', age: 22 }
    ];
    @ViewChildren(Item,  {descendants: true}) itemList: QueryList<Item>;
    constructor() {}

    ngAfterViewInit() {
        console.log(this.itemList);
        this.itemList.changes.subscribe(() => console.log(this.itemList));
    }

    addParent() {
        this.users.push({ name: 'Parent ' + (this.users.length + 1), age: 18 });
    }
}

bootstrap(AppComponent);

我在addParent()时更新,但在addChild()时没有更新。看起来QueryList仅为顶级更改订阅。任何想法如何使它工作?

1 个答案:

答案 0 :(得分:3)

我认为它比使用@ViewChildren / @ViewQuery更通用。

事实上,它是Angular2处理变化检测的方式。我的意思是对象内的更新不会触发更改检测,但是如果你更新整个引用,它就会发生。

所以你需要重构一下你的removeDynamic方法:

addChild() {
  this.children.push({ name: 'Child' + (this.children.length + 1), age: 18 });
  this.children = this.children.slice();
}

addParent() {
  this.users.push({ name: 'Parent ' + (this.users.length + 1), age: 18 });
  this.users = this.users.slice();
}

有关slice方法的使用,请参阅此答案:

以下是Angular团队对此行为的回答:https://github.com/angular/angular/issues/6458

希望它可以帮到你, 亨利