Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template reference variable as @Input() for other component

Angular v5.0.1

I have this template on a component

<div #content>some content</div>
<some-component [content]="content"></some-component>

I want to pass the reference of #content variable to SomeComponent via @Input()content but I'm not sure what type the variable is.

From what I searched on the web it appears to be ElementRef so I did

  @Input()
  component: ElementRef;
  ngOnInit() {
    console.log(this.component); // this prints the html element on console
    console.log(this.component.nativeElement); // this prints undefined
  }

but this.component.nativeElement is undefined

Doing more tests it appears that this.component is actually the native element

Doing something like this works and actually the background color is changed (this is just for testing purposes I'm not interesting in actually changing the color this way)

this.component.style.backgroundColor = 'red';

While I got this working the way I wanted I have a few question to better understand how things work.

  1. Is #content the native element and not the ElementRef ?
  2. Is this the valid Angular way of passing a reference variable to another component?

If you think this approach is wrong or is a better way of doing this please provide some valid example.

like image 700
Doua Beri Avatar asked Nov 14 '17 11:11

Doua Beri


People also ask

Can we use template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

How do you read a template reference variable in component?

Usually, the reference variable can only be accessed inside the template. However, you can use ViewChild decorator to reference it inside your component. @ViewChild('firstNameInput') nameInputRef: ElementRef; After that, you can use this.

What is true about template reference variables?

A template reference variable is a feature that allows us to gain access to a part of our template. This could be an element, component, or could be a directive.


1 Answers

ngOnInit() might be too early. ngAfterViewInit() might work:

ngAfterViewInit() {
  console.log(this.component); // this prints the html element on console
  console.log(this.component.nativeElement); // this prints undefined
}

Is #content the native element and not the ElementRef ?

If #content is on a plain element, it is the nativeElement.
If the element hosts a component or directive, you'll get the component or directive instance.

like image 61
Günter Zöchbauer Avatar answered Oct 20 '22 22:10

Günter Zöchbauer