Passionate Coder
Passionate Coder

Reputation: 7294

Element Ref variables not getting when passed by component

I have a component in which i am passing a component by reference. I am able to get component but the properties inside passed component getting undefined

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) 

  }
}

ContainerComponent.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>

Demo Link

https://stackblitz.com/edit/angular-qhybe9?embed=1&file=src/app/container/container.component.ts

console.log.(this.cmpRef) gives below result

ContainerComponent {}one: ElementRef {nativeElement: div}two: ElementRef {nativeElement: div}__proto__: Object

But when i try to access this.cmpRef.one i am getting undefined

Upvotes: 0

Views: 54

Answers (1)

Alexander
Alexander

Reputation: 272

Use ngAfterViewInit() for this.

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

When you call console.log(this.cmpRef) in the ngOnChanges hook ContainerComponent view does not exist yet.

Upvotes: 2

Related Questions