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.
#content
the native element and not the ElementRef
?If you think this approach is wrong or is a better way of doing this please provide some valid example.
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 .
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.
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.
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 theElementRef
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With