2017年更新:
ViewChild将是访问Dom元素的最佳方式.
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();
- }
- }
- <div #itemId>{{ (items()) }}</div>
您可以通过ViewChild访问Element:
- import {ViewChild} from '@angular/core';
- @ViewChild('itemId') itemId;
- ngAfterViewInit() {
- console.log(this.itemId.nativeElement.value);
- }