我有三个嵌套组件,称为level0,level1和level2,定义如下:
@Component({ selector: 'level2',template: `<div>I am level 2</div>`,}) export class Level2 { getName(){ return "my name is 'TWO'"; } }
@Component({ selector: 'level1',template: `<div>I am level 1<level2></level2></div>`,directives: [Level2] }) export class Level1 { getName(){ return "my name is 'ONE'"; } }
@Component({ selector: 'level0',template: `<div>I am level 0<level1></level1></div>`,directives: [Level1,Level2] }) export class App { @ViewChild(Level1) level1:Level1; @ViewChild(Level2) level2:Level2; ngAfterViewInit() { if(this.level1){var name1 = this.level1.getName();} if(this.level2){var name2 = this.level2.getName();} console.log("name1",name1); console.log("name2",name2); } }@H_404_7@在控制台中,我希望看到:
name1 my name is 'ONE' name2 my name is 'TWO'@H_404_7@但我改为:
name1 my name is 'ONE' name2 undefined@H_404_7@我错过了什么?为什么Level0组件不能通过@ViewChild访问Level2? @H_404_7@有没有办法访问Level0中的Level2方法? @H_404_7@Here is the plnkr
我认为目前不可能.
@H_404_7@ViewQueryMetadata API doc说如下:
@H_404_7@Supports the same querying parameters as QueryMetadata,except descendants.@H_404_7@QueryMetadata API doc有这个后代的例子:
@H_404_7@Configure whether query looks for direct children or all descendants of the querying element,by using the descendants parameter. It is set to false by default.
@H_404_7@… code here not shown …
@H_404_7@When querying for items,the first container will see only a and b by default,but with Query(TextDirective,{descendants: true})
it will see c too.