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();
}
}
ts, one stands out among the rest: HTMLElement . This type is the backbone for DOM manipulation with TypeScript.
React automatically updates the DOM to match your render output, so your components won't often need to manipulate it. However, sometimes you might need access to the DOM elements managed by React—for example, to focus a node, scroll to it, or measure its size and position.
For manipulating DOM you need a scripting language like JS, VB etc.
<div #itemId>{{ (items()) }}</div>
You can access the Element via ViewChild:
import {ViewChild} from '@angular/core';
@ViewChild('itemId') itemId;
ngAfterViewInit() {
console.log(this.itemId.nativeElement.value);
}
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