2017年更新: ViewChild将是访问Dom元素的最佳方式。
2016年发布的问题:
我尝试了以下两种方法,只有方法2可行。但我不想要重复的代码:document.getElementById()在每个方法中。我更喜欢方法1,但为什么方法1不起作用?
在Angular2中有没有更好的方法来操作DOM?
.html文件:
<video id="movie" width="480px" autoplay>
<source src="img/movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
方法1:
...
class AppComponent {
videoElement = document.getElementById("movie");
playVideo() {
this.videoElement.play();
}
}
方法2:
...
class AppComponent {
playVideo() {
var videoElement = document.getElementById("movie");
videoElement.play();
}
}
答案 0 :(得分:10)
<div #itemId>{{ (items()) }}</div>
您可以通过ViewChild访问Element:
import {ViewChild} from '@angular/core';
@ViewChild('itemId') itemId;
ngAfterViewInit() {
console.log(this.itemId.nativeElement.value);
}
答案 1 :(得分:-1)
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