我有三个嵌套组件,称为和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
组件Level2
不能通过@ViewChild
?
有没有办法访问中的Level2
方法Level0
?