element.style 在打字稿 [Angular 5] 中不起作用



>我正在尝试在我的打字稿中用javascript设置元素的样式,但它不起作用。这是我尝试做的:

const element = document.getElementsByClassName('current');
element.style.backgroundColor = "" + this.styles.style.mainIdentifyingColor;

但我得到错误:

属性"style"在 HTMLCollectionOf 上不存在。

我也尝试过使用setAttribute,但同样的事情。

我知道我并没有完全回答你的问题,但你试过使用 NgStyle 吗? 文档


.HTML

<div [ngStyle]="{ 'background-color': myCustomColor }"> 
</div>

TS

someFunctionToBeCalled() {
this.myCustomColor=this.styles.style.mainIdentifyingColor;
}

您需要遍历HTMLCollection中包含的HTMLElements数组,并为每个数组设置 style 属性。

如果您更喜欢只在类名为current的第一个(或仅,如您所见)元素上设置样式,那么您可以这样做:

const element = document.getElementsByClassName('current');
element[0].style.backgroundColor = "" + this.styles.style.mainIdentifyingColor;

最新更新