Angular2+Typescript:如何操作 DOM 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35801420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2+Typescript: how to manipulate DOM element?
提问by Ng2-Fun
Update in 2017: ViewChild will be the best way to access Dom element.
2017 年更新:ViewChild 将是访问 Dom 元素的最佳方式。
Question posted in 2016:
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?
我尝试了以下两种方法,只有方法 2 有效。但我不希望每个方法中都有重复的代码:document.getElementById()。我更喜欢方法 1,但为什么方法 1 不起作用?
Are there any better ways to manipulate DOM in Angular2?
有没有更好的方法在 Angular2 中操作 DOM?
.html file:
.html 文件:
<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();
}
}
回答by mahdi kallel
<div #itemId>{{ (items()) }}</div>
You can access the Element via ViewChild:
您可以通过 ViewChild 访问 Element:
import {ViewChild} from '@angular/core';
@ViewChild('itemId') itemId;
ngAfterViewInit() {
console.log(this.itemId.nativeElement.value);
}
回答by Pardeep Jain
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)]
:
根据您的问题,您想将代码的一些公共部分用于多种方法。但你没有成功。只需声明一个变量并为该变量分配一些值,然后您就可以将该变量用于多个方法中,或者我们可以说使用以下两种方式绑定角度数据绑定此变量值[(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
这是相同http://plnkr.co/edit/Y80SsPCUTx1UP5tYksIy?p=preview 的工作演示