我想创建一个目录树,并且无论级别如何都可以访问所有项目,但是当我动态添加二级子级时,@ 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);
Run Code Online (Sandbox Code Playgroud)
我在addParent()时更新,但在addChild()时没有更新.看起来QueryList仅为顶级更改订阅.任何想法如何使其工作?
我认为它比@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();
}
Run Code Online (Sandbox Code Playgroud)
关于该方法的使用请参阅这个答案slice:
以下是 Angular 团队关于此行为的答案:https ://github.com/angular/angular/issues/6458 。
希望它对你有帮助,蒂埃里
| 归档时间: |
|
| 查看次数: |
5231 次 |
| 最近记录: |