gpt4 book ai didi

dom - Angular2+ typescript : how to manipulate DOM element?

转载 作者:太空狗 更新时间:2023-10-29 17:24:54 25 4
gpt4 key购买 nike

2017 年更新:ViewChild 将是访问 Dom 元素的最佳方式。

2016 年发布的问题:

以下两种方法我都试过了,只有方法2有效。但是我不希望每个方法中都有重复的代码:document.getElementById()。我更喜欢方法一,但为什么方法一不行?

有没有更好的方法在 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>

方法一:

...
class AppComponent {
videoElement = document.getElementById("movie");

playVideo() {
this.videoElement.play();
}
}

方法二:

...
class AppComponent {

playVideo() {
var videoElement = document.getElementById("movie");
videoElement.play();
}
}

最佳答案

<div #itemId>{{ (items()) }}</div>

您可以通过 ViewChild 访问元素:

import {ViewChild} from '@angular/core';

@ViewChild('itemId') itemId;

ngAfterViewInit() {
console.log(this.itemId.nativeElement.value);
}

关于dom - Angular2+ typescript : how to manipulate DOM element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com