angular – @ViewChild:访问grand-child方法

前端之家收集整理的这篇文章主要介绍了angular – @ViewChild:访问grand-child方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个嵌套组件,称为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);
  }
}

在控制台中,我希望看到:

name1 my name is 'ONE'
name2 my name is 'TWO'

但我改为:

name1 my name is 'ONE'
name2 undefined

我错过了什么?为什么Level0组件不能通过@ViewChild访问Level2?

有没有办法访问Level0中的Level2方法

Here is the plnkr

我认为目前不可能.

ViewQueryMetadata API doc说如下:

Supports the same querying parameters as QueryMetadata,except descendants.

@H_502_32@

QueryMetadata API doc有这个后代的例子:

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.

… code here not shown …

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.

@H_502_32@
原文链接:https://www.f2er.com/angularjs/142250.html

猜你在找的Angularjs相关文章