Angular2+Typescript: how to manipulate DOM element?

Viewed 20272

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

Question posted in 2016:

I have tried the following two methods, only method 2 works. But I don't want the repeated code: document.getElementById() in each method. I prefer method 1, but why method 1 doesn't work?

Are there any better ways to manipulate 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();
    }
}
2 Answers
Related