首页 > 解决方案 > 组件传递时未获取元素引用变量

问题描述

我有一个组件,我在其中通过引用传递一个组件。我能够获取组件,但传递的组件内部的属性变得未定义

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

标签: javascriptangular

解决方案


用于ngAfterViewInit()此。

ngAfterViewInit() {
    console.log(this.cmpRef)
}

当你console.log(this.cmpRef)ngOnChanges钩子ContainerComponent视图中调用时还不存在。


推荐阅读