如何在打字稿/角度中设置子HTML元素的样式 [英] How to style a Child html element in typescript / angular

查看:70
本文介绍了如何在打字稿/角度中设置子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的正确方法.

感谢您的帮助,并请记住,我是angel 5和打字稿的新手.

解决方案

为元素设置样式的推荐方法不是使用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');
    }

i am using ionic 3 to build a hybrid mobile app, one of the requirements is that the user have the ability to change the toolbar color dynamically. after the page is rendered that's how the html looks like:

<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>

i tried to do the following: document.getElementById('divICanControl').childNodes[0].style.backgroundColor = this.someColor;

it worked occasionally but it created the following error in vscode: [ts] Property 'style' does not exist on type 'Node'.

and it stopped the build of the app.

i am now searching for the right way to manipulate the dom using angular.

thank you for your help and please keep in mind that i am new to angular 5 and typescript.

解决方案

The recommended way to style elements is not with document....style. It's with renderer. Observe:

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

这篇关于如何在打字稿/角度中设置子HTML元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆