如何在typescript / angular中设置子html元素的样式

5
我正在使用Ionic 3来构建混合移动应用程序,其中一个要求是用户能够动态更改工具栏的颜色。页面呈现后,HTML如下所示:
//我可以控制这个div
//但这个是由框架生成的,这是更改工具栏背景颜色的div
我尝试了以下方法:
document.getElementById('divICanControl').childNodes [0] .style.backgroundColor = this.someColor;
它有时候起作用,但在VSCode中会创建以下错误:
[ts]属性“style”不存在于类型“Node”上。
并且它会停止应用程序的构建。
我现在正在寻找使用Angular操作DOM的正确方法。
谢谢您的帮助,请记住我是新手Angular 5和TypeScript。
1个回答

5
推荐的样式元素的方式不是使用document....style,而是使用renderer。请看下面的示例:
<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');
    }

6
我建议使用 ViewChild 来获取 first,而不是通过 DOM 进行选择。 - Explosion Pills
谢谢您,David Anthony Acosta,您解决了我的问题。 - George
@ExplosionPills,药丸,我一定会研究的。 - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接