how to set multiple CSS style properties in typescript for an element?

Srinivasan Natarajan picture Srinivasan Natarajan · Jun 6, 2016 · Viewed 66.3k times · Source

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

Answer

theUtherSide picture theUtherSide · May 24, 2017

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