Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2+Typescript: how to manipulate DOM element?

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();
    }
}
like image 417
Ng2-Fun Avatar asked Mar 04 '16 16:03

Ng2-Fun


People also ask

Can TypeScript be used for DOM manipulation?

ts, one stands out among the rest: HTMLElement . This type is the backbone for DOM manipulation with TypeScript.

Can you manipulate the DOM in react?

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.

Can DOM be manipulated without JavaScript?

For manipulating DOM you need a scripting language like JS, VB etc.


1 Answers

<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);
    }
like image 169
mahdi kallel Avatar answered Oct 17 '22 07:10

mahdi kallel