【问题标题】:How to style a Child html element in typescript / angular如何在打字稿/角度设置子html元素的样式
【发布时间】:2018-06-24 05:21:48
【问题描述】:

我正在使用 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'.

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

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

感谢您的帮助,请记住,我是 Angular 5 和打字稿的新手。

【问题讨论】:

    标签: angular typescript dom visual-studio-code ionic3


    【解决方案1】:

    推荐的元素样式方法不是使用文档....样式。它与渲染器。观察:

    <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');
        }
    

    【讨论】:

    • 我建议使用ViewChild 来获取first 而不是通过DOM 选择它。
    • 谢谢@David Anthony Acosta 你解决了我的问题
    • @ExplosionPills Pills 我一定会调查的
    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 2011-12-28
    • 2013-08-16
    相关资源
    最近更新 更多