Let's say I have a component like this in Angular 2.
@Component ({ directives: [Timeline, VideoPlayer], template: `<div> <span id="myId"></span> <videoplayer [mode]="mode"></videoplayer> <timeline [mode]="mode"></timeline> </div>`, }) export class VideoEditor { }
How can I get a reference to an element from a template? For instance, how do I get a reference to a <span>
?
I found two approaches so far:
1) Get a reference using ElementRef
export class VideoEditor { constructor (private el: ElementRef) { el.nativeElement.getElementsBy.....; } }
2) Using ViewChild
export class VideoEditor { @ViewChild(Timeline) timeline: Timeline; ngAfterViewInit () { this.timeline; } }
3) Using local template variable
1) What I don't like about a first approach is that I need to do getElementsBy...
-like function.
2) Regarding a second one, I don't know how to get an access to a HTML element, I can only get access to another sub-component. And what if I have more subcomponents of a same type?
3) Local template variable only works within a templates, am I right?
What is the best way to get a reference to a template in Angular 2? I'd like to have something like React has https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
<input ref="myInput" />
var input = this.refs.myInput; var inputValue = input.value; var inputRect = input.getBoundingClientRect();
You can use @ViewChild('varName')
with a template variable (<tag #varName>
) to get a specific element when you have more than one of the same type. You should try to avoid direct access anyway, use bindings instead if possible.
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