如何在打字稿/角度设置子html元素的样式 [英] How to style a Child html element in typescript / angular
问题描述
我正在使用 ionic 3 构建一个混合移动应用程序,其中一个要求是用户具有动态更改工具栏颜色的能力.页面渲染后,html 是这样的:
<div id="divICanControl">//这个div我可以控制
我尝试执行以下操作:document.getElementById('divICanControl').childNodes[0].style.backgroundColor = this.someColor;
它偶尔会起作用,但它在 vscode 中产生了以下错误:[ts] 类型节点"上不存在属性样式".
它停止了应用程序的构建.
我现在正在寻找使用 angular 操作 dom 的正确方法.
感谢您的帮助,请记住,我是 Angular 5 和打字稿的新手.
推荐的元素样式方法不是使用文档....样式.它与渲染器.观察:
<div id="first">第一的<div id="秒">第二</div></div><button(click)="change()">更改</button>从'@angular/core'导入{组件,OnInit,Renderer2};构造函数(私有渲染器:Renderer2){}改变() {常量父: 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屋!