Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.
public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
if (attrs !== undefined) {
Object.keys(attrs).forEach((key: string) => {
element.style[key] = attrs[key];
});
}
}
for the above code i need to pass the parameters as
let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {font-size:'12px', color : 'red' , margin-top: '5px'});
But the above code throws error(tslint) as Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration.
Please help me !!!
Try using setAttribute
. TypeScript does not have the style
property on Element
.
element.setAttribute("style", "color:red; border: 1px solid blue;");
Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263
The API you were searching for is: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: string }): void {
for(const [key, value] of Object.entries(attrs)) {
element.style.setProperty(key, value);
}
}
And hyphen is not allowed in object keys, so use ' here, too:
let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With