Version 5.0.1 of Angular
In one of my components I have the following template:
<div #content>some content</div>
<some-component [content]="content"></some-component>
I am trying to pass the reference of the #content
variable to SomeComponent
using @Input()content
, but I'm unsure of the variable type.
After researching online, it seems that it should be ElementRef
, so I tried the following:
@Input()
component: ElementRef;
ngOnInit() {
console.log(this.component); // this prints the html element on console
console.log(this.component.nativeElement); // this prints undefined
}
However, this.component.nativeElement
returns undefined.
Further testing revealed that this.component is actually the native element.
Executing something like this successfully changes the background color (for testing purposes only - not for actual use):
this.component.style.backgroundColor = 'red';
Although I achieved the desired outcome with this method, I still have a few questions to deepen my understanding.
- Is
#content
considered the native element rather than theElementRef
? - Is this the correct way in Angular to pass a reference variable to another component?
If you believe there is a more appropriate approach or have a better example to provide, please share some valid insights.