如何在打字稿/角度中设置子HTML元素的样式

乔治

我正在使用ionic 3构建混合移动应用程序,要求之一是用户必须能够动态更改工具栏颜色。页面呈现后,html的外观如下:

<div id="divICanControl"> //this div i can control <div> //but this one is generated by the framework and this is the div that change the background color of the toolbar </div> </div>

我尝试执行以下操作: document.getElementById('divICanControl').childNodes[0].style.backgroundColor = this.someColor;

它偶尔起作用,但是在vscode中创建了以下错误: [ts] Property 'style' does not exist on type 'Node'.

它停止了应用程序的构建。

我现在正在寻找使用角度操作dom的正确方法。

感谢您的帮助,并请记住,我是Angle 5和Typescript的新手。

戴维·安东尼·阿科斯塔

推荐使用样式元素的方式不是document .... style。它与渲染器一起使用。观察:

<div id="first">
    first
    <div id="second">
        second
    </div>
</div>

<button (click)="change()">Change</button>


import { Component, OnInit, Renderer2 } from '@angular/core';

    constructor(private renderer: Renderer2) { }

    change() {
        const parent: HTMLElement = document.getElementById('first');
        const child = parent.children[0];
        this.renderer.setStyle(child, 'background-color', 'red');
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章