假设我们有一个名为TopComponent
使用这样的模板:
<ng-template #top>
<inner-selector #inner></inner-selector>
</ng-template>
它的代码很简单:
//... imports ...
@Component({
// selector, styles etc
})
export class TopComponent implements AfterViewInit {
@ViewChild('top') topComp : NgbModal;
// NgbModal is a type provided by some 3rd-party library
// I can't modify it
ngAfterViewInit() {
// let's access the #inner component from here
}
}
我可以访问#top
使用此代码的组件:
@ViewChild('top') topComponent: TopComponent;
我怎样才能访问#inner
来自同一类的组件?
我尝试使用@ContentChild('inner')
但仍然得到undefined
.
PS.作为解决方法,我可以创建另一个组件,在<ng-template>
并从中访问所有必要的子项。但这可以通过某种方式避免吗?
模板#top需要加载到某个容器中以存在于 DOM 中并由@ViewChild。
最简单的方法是使用简单的结构指令。
下面的例子NotReady是一个布尔值,在 ngInit 完成后设置为 false。
<div *ngIf="notReady else top">
loading...
</div>
<ng-template #top>
<inner-selector #inner></inner-selector>
</ng-template>
请注意,@ViewChild('top') 需要映射为静态:假,因为它可能在 ngOnInit() 之后才可用/存在。
然后在每个更改检测周期搜索 #top,这在使用 *ngIf 等条件指令时很有用。
//... imports ...
@Component({
// selector, styles etc
})
export class TopComponent implements AfterViewInit {
notReady: boolean = true;
@ViewChild("top", { static: false }) topComp : NgbModal;
// NgbModal is a type provided by some 3rd-party library
// I can't modify it
ngInit(){
this.notReady = false;
}
ngAfterViewInit() {
// let's access the #inner component from here
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)