Angular2 Typescript:如何操纵DOM元素?

前端之家收集整理的这篇文章主要介绍了Angular2 Typescript:如何操纵DOM元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
2017年更新:
ViewChild将是访问Dom元素的最佳方式.

2016年发布的问题:

我尝试了以下两种方法,只有方法2可行.但我不想在每个方法中重复代码:document.getElementById().我更喜欢方法1,但为什么方法1不起作用?

有没有更好的方法来操纵Angular2中的DOM?

.html文件

  1. <video id="movie" width="480px" autoplay>
  2. <source src="img/movie.mp4" type="video/mp4">
  3. Your browser does not support the video tag.
  4. </video>

方法1:

  1. ...
  2. class AppComponent {
  3. videoElement = document.getElementById("movie");
  4.  
  5. playVideo() {
  6. this.videoElement.play();
  7. }
  8. }

方法2:

  1. ...
  2. class AppComponent {
  3.  
  4. playVideo() {
  5. var videoElement = document.getElementById("movie");
  6. videoElement.play();
  7. }
  8. }
  1. <div #itemId>{{ (items()) }}</div>

您可以通过ViewChild访问Element:

  1. import {ViewChild} from '@angular/core';
  2.  
  3. @ViewChild('itemId') itemId;
  4.  
  5. ngAfterViewInit() {
  6. console.log(this.itemId.nativeElement.value);
  7. }

猜你在找的Angularjs相关文章