首先,这种行为只发生在beta16中,之前的版本正在按预期工作。
@Query还会找到后代元素的模板元素,考虑在内容中查找模板元素的组件;
export class Container {
constructor(@Query(TemplateRef) templates: QueryList<TemplateRef>) {
templates.changes.subscribe(_ => {
console.log(templates.length);
});
}
}
@Component({
selector: 'my-app',
template: `<container>
<template></template>
<child>
<template></template>
</child>
</container>`,
directives: [Container,Child]
http://plnkr.co/edit/sANW6mfss5EvPfWpXRde
我希望在控制台上记录“1”,但会记录“2”。还发现了孩子的模板。
但是用一些随机组件替换模板元素,例如otherchild,产生预期的结果;
export class Container {
constructor(@Query(OtherChild) templates: QueryList<OtherChild>) {
templates.changes.subscribe(_ => {
console.log(templates.length);
});
}
}
@Component({
selector: 'my-app',
template: `<container>
<otherchild></otherchild>
<child>
<otherchild></otherchild>
</child>
</container>`,
directives: [Container,Child,OtherChild]
})
http://plnkr.co/edit/OzXjz8niAurzr6CZIoes
打印“1”,因为容器只有一个其他子容器。
因此,模板元素会产生混淆。我想知道这是一个错误还是预期的行为。
答案 0 :(得分:1)
@Query()
,暂时弃用@ContentChildren()
。
提示:只有在调用@ContentChildren()
之后才能在构造函数中访问ngAfterContentInit()
的结果。
同样需要descendants: true
传递给直接的孩子而不是所有的后代(这可能是改变了@Query()
- 我不知道这个参数现在是否也可用)
export class Container {
@ContentChildren(OtherChild, {descendants: true}) templates;
ngAfterContentInit( ) {
console.log(this.templates.length);
this.templates.changes.subscribe(_ => {
console.log(templates.length);
});
}
}
我也可以使用@ContentChildren()
重现您的问题。此代码还会打印 2 ,但应打印 1 。我认为这是由于测试版16中@ContentChilren()
和@ViewChildren()
的更改而导致的错误。
export class Container {
@ContentChildren(TemplateRef, {descendants: false}) templates;
ngAfterContentInit() {
console.log(this.templates.length);
this.templates.changes.subscribe(_ => {
console.log(templates.length);
});
}
}