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(); } }
source share