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 !!!
Just a little late to the party, but anyway...
The actual problem is not that
style
is not defined onElement
. The wordElement
at the beginning ofElement implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration
is just the first word in a sentence and therefore uppercased. Means it does not relate in any way to theElement
object - which is quite confusing.However, the error message means that you are trying to access a property using the subscript operator
[]
with an incorrectly typed index. In your case yourkey
is of typestring
butHTMLElement.style
is aCSSStyleDeclaration
object which has an index signature of[index: number]: string
and consequently requires your key to be of typenumber
.The index signature comes from the
typescript/lib/lib.dom.d.ts
declaration file in your TypeScript installation. There you will findCSSStyleDeclaration
.So what you can do is simply cast to
any
like so:It's not the best solution but it works and is straightforward. It also does not require you to stringify your styles like it would be necessary when you use
element.setAttribute
.The API you were searching for is: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
And hyphen is not allowed in object keys, so use ' here, too:
I hope this helps you or someone else...
You can achieve this using a
HTLMDivElement
and theCSSStyleDeclaration
contained within it. eg.This also applies to other classes that inherit from
HTMLElement
and have astyle
property (for exampleHTMLBodyElement
.Try using
setAttribute
. TypeScript does not have thestyle
property onElement
.Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263