How to style a Child html element in typescript / angular

本秂侑毒 提交于 2020-01-24 10:55:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/48265353/how-to-style-a-child-html-element-in-typescript-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!