Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: What is the best way to get a reference of a template element [duplicate]

Tags:

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(); 
like image 462
Jan Vorcak Avatar asked Jan 06 '16 15:01

Jan Vorcak


1 Answers

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.

like image 63
Günter Zöchbauer Avatar answered Oct 08 '22 06:10

Günter Zöchbauer