7

I'm trying the get an ElementRef for a child component from its parent component.

@Component({
moduleId: module.id,
selector: 'parent',
templateUrl: 'parent.component.html',
directives: [
  Child1Component,
  Child2Component
  ]
})

In the html for Child1Component I have

  <button class="btn btn-primary" #myRef>Select File</button>

In the class for the parent:

export class ParentComponent implements OnInit {
  @ViewChild('myRef') myRef: ElementRef;
  // ...

But of course when I try to access the child ElementRef in the parent class...

ngAfterViewInit() {
  console.log(this.myRef.nativeElement);

...I get undefined. How should I get the ElementRef? Thanks!

1
  • 2
    I'm not aware of any way for a parent component to be able to reference a local template variable defined in a child component template. Consider having the parent get a reference to the child component using @ViewChild, then you can call a method on the child component to manipulate the element of interest. Commented May 20, 2016 at 14:47

3 Answers 3

6

You can now do this.

@ViewChild('myRef', {read: ElementRef}) myRef: ElementRef

By default Angular will grab the component reference if your template reference variable is attached to a custom component. The read option tells angular which token to pull, so you can explicitly tell it to pull the ElementRef token instead of the class instance of whatever component you are trying to read.

Sign up to request clarification or add additional context in comments.

Comments

2

In my case I needed

@ViewChild('myRef', { static: true, read: ElementRef }) myRef!: ElementRef

Comments

0

try using ContentChild instead of ViewChild

import { Component, ContentChild, ElementRef, OnInit } from '@angular/core';
...

export class ParentComponent implements OnInit {
  @ContentChild('myRef') myRef: ElementRef;
  // ...

  ngAfterViewInit() {
    console.log(this.myRef.nativeElement);
  }

}

1 Comment

@chris_r: That last comment of yours in your recently deleted question was completely uncalled for and is the sort of comment that can get you banned from this site. Moderators have been notified of your behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.