javascript - 组件传递时未获取元素引用变量
问题描述
我有一个组件,我在其中通过引用传递一个组件。我能够获取组件,但传递的组件内部的属性变得未定义
app.component.html
<app-home [cmpRef]="cmp"></app-home>
<app-container #cmp></app-container>
home.component.ts
export class HomeComponent {
@Input() cmpRef: any
ngOnChanges() {
console.log(this.cmpRef)
}
}
容器组件.ts
export class ContainerComponent {
@ViewChild('one',{static:false}) one : any;
@ViewChild('two',{static:false}) two : any;
}
container.component.html
<div #one>
This is div One
</div>
<div #two>
This is div Two
</div>
演示链接
https://stackblitz.com/edit/angular-qhybe9?embed=1&file=src/app/container/container.component.ts
console.log.(this.cmpRef)
给出以下结果
ContainerComponent {}one: ElementRef {nativeElement: div}two: ElementRef {nativeElement: div}__proto__: Object
但是当我尝试访问this.cmpRef.one
时,我得到了undefined
解决方案
用于ngAfterViewInit()
此。
ngAfterViewInit() {
console.log(this.cmpRef)
}
当你console.log(this.cmpRef)
在ngOnChanges
钩子ContainerComponent
视图中调用时还不存在。
推荐阅读
- datatables - 如何在 DataTables 中获得活动/显示的响应列
- python - 基于公共列ID的两个熊猫数据框之间的vlookup类型操作
- scala - 在运行时创建具有相同内部内容的对象
- amazon-web-services - 如何使用创建它们的 IAM 用户标记 ec2 实例和资源?
- c# - 遍历通过反射动态调用的列表
- neo4j - Neo4j APOC 使用主键而不是内部 id 导出/导入
- asp.net - NWebsec CSP for Google Analytics on ASP.NET -> 如何包含所有 Google 域
- python - Pandas 根据时间戳分配 5-1 范围内的点,最近获得最大点
- apache-flink - kafka flink连接报错显示NoSuchMethodError
- c++ - 具有多个参数的模板类特化,其中一个模板参数是模板本身