Ng2-Fun
Ng2-Fun

Reputation: 3393

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

Upvotes: 6

Views: 20363

Answers (2)

mahdi kallel
mahdi kallel

Reputation: 453

<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);
    }

Upvotes: 11

Pardeep Jain
Pardeep Jain

Reputation: 86750

According to your question you want to use some common portion of code into multiple methods. but you got unsuccessful. just declare one single variable and assign some values to that variable then you will be able to use that variable into multiple methods like this or we can say bind this variable value with two way data binding of 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>

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

Upvotes: -1

Related Questions