Angular2 + Typescript: how to manipulate a DOM element?

2017 update: ViewChild will be the best way to access the Dom element.

Question published in 2016:

I tried the following two methods, only method 2 works. But I do not want to repeat the code: document.getElementById () in each method. I prefer method 1, but why does method 1 not work?

Are there more efficient ways to manipulate the DOM in Angular2?

.html file:

<video id="movie" width="480px" autoplay> <source src="img/movie.mp4" type="video/mp4"> Your browser does not support the video tag. </video> 

Method 1:

 ... class AppComponent { videoElement = document.getElementById("movie"); playVideo() { this.videoElement.play(); } } 

Method 2:

 ... class AppComponent { playVideo() { var videoElement = document.getElementById("movie"); videoElement.play(); } } 
+6
source share
2 answers
 <div #itemId>{{ (items()) }}</div> 

You can access the item through ViewChild:

 import {ViewChild} from '@angular/core'; @ViewChild('itemId') itemId; ngAfterViewInit() { console.log(this.itemId.nativeElement.value); } 
+10
source

According to your question, you want to use some common piece of code for several methods. but you were unsuccessful. just declare one single variable and assign some values ​​to this variable, then you can use this variable in several methods like this, or we can say to bind this variable value with two-way data binding to angular using [(ngModel)] :

  class A { abc:string = null; abc2:string = null; abcFun(){ console.log(this.abc) } bcdFun(){ console.log(this.abc) } // second method using javascript as your way abcFun2(){ this.abc2 = document.getElementById('abc2').value; console.log(this.abc2); } bcdFun2(){ console.log(this.abc2); } } <input type="text" id="abc" [(ngModel)]="abc"> {{abc}} <button (click)="abcFun()">ABC FUN</button> <button (click)="bcdFun()">BCD FUN</button> <input type="text" id="abc2"> {{abc2}} <button (click)="abcFun2()">ABC FUN</button> <button (click)="bcdFun2()">BCD FUN</button> 

the demo here works for the same http://plnkr.co/edit/Y80SsPCUTx1UP5tYksIy?p=preview

-1
source

All Articles