Try using setAttribute. TypeScript does not have the style property on Element.
Copyelement.setAttribute("style", "color:red; border: 1px solid blue;");
Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263
Answer from theUtherSide on Stack Overflowhow to set multiple CSS style properties in typescript for an element? - Stack Overflow
html - Applying CSS to Element created in TypeScript - Stack Overflow
CSS in TS
reactjs - How to import CSS modules with Typescript, React and Webpack - Stack Overflow
Videos
» npm install typescript-plugin-css-modules
Try using setAttribute. TypeScript does not have the style property on Element.
Copyelement.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
Copypublic 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:
Copylet elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
You can directly add class to the element, created in the TypeScript file.
TypeScript Code
test.textContent = "Created in TS";
test.setAttribute("class","MyClass");
container.append(test);
CSS
.MyClass {
color: green !important;
}
Why not work:
The way Angular manage the .css (to isolate the .css of each element) is adding a prefix in .css. So if you check the .html using F12 in your navigator
You see a .css like
p[_ngcontent-ng-c474887881] {
color: red;
}
And a .html like
<div _ngcontent-ng-c474887881="" class="testContainer">
<p _ngcontent-ng-c474887881="">Created in HTML</p>
<p>Created in TS</p>
</div>
(the _ng-content-ng-c474887881] can be another one, it's only to explain me.
So, when you create using simple javascript your "divs" has not the attribute _ngcontent-ng-..., and not get the .css
Solutions:
You can use a global .css (adding in styles.css or using ViewEncapsulation.None), but in this case the .css is applied to all the application, and to make the .css it's only to the element created you need add a class to your element to be more specific the .css
The another way is use Renderer2
const container = document.querySelector('.testContainer') //(*) const div = this.renderer.createElement('p'); const text = this.renderer.createText('Created in TS by renderer2'); this.renderer.appendChild(div, text); this.renderer.appendChild(container, div);(*) I prefer use a template reference variable and ViewChild,
In your .html
<div #container> <p>Created in HTML</p> <!-- Created in TS--> </div>In .ts
//I use static true because the div is NOT under a *ngIf @ViewChild('container',{static:true}) container!:ElementRef //and use this.renderer.appendChild(this.container.nativeElement, div);
Honest question: why is this a thing? I've been working with CSS for years and haven't tried anything related to CSS in TS or JS. If you are able to manage your styles with utility classes or classes for components in CSS directly, why would you use something like this?
I'm in no way criticizing the technology, I just want to know what problems tools like this one solve. If I'm able to style all my views with CSS with no problem, should I learn something like this and move to this approach?
Sprinkles - Atomic CSS in TSNow in the year 2021, all you need to do is add a src/Globals.d.ts to your project with these lines:
declare module "*.module.css";
declare module "*.module.scss";
// and so on for whatever flavor of css you're using
Then install and add
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
}
}
to your tsconfig.
Example of this correctly functioning in VS code after making that simple change (root is a class defined in my stylesheet):

Webpack and tsc also compile correctly on the command line.
A) As you are saying, there is one simplest (not best) option to use require:
const css = require('./component.css')
- We need to have typings for
requireas it's not standard feature in typescript. Simplest typing for this specific require may be:
declare function require(name: string): string;Webpack will then compile typescript and use modules properly - BUT without any IDE help and class names checks for build.
B) There is better solution to use standard import:
import * as css from './component.css'
- enables full class names IntelliSense
- requires types definition for each css file, otherwise
tsccompiler will fail
For proper IntelliSense, Webpack needs to generate types definition for each css file:
Use webpack typings-for-css-modules-loader
webpackConfig.module.loaders: [ { test: /\.css$/, loader: 'typings-for-css-modules?modules' } { test: /\.scss$/, loader: 'typings-for-css-modules?modules&sass' } ];Loader will generate
*.css.d.tsfiles for each of css files in your codebase- Typescript compiler will understand that css import will be module with properties (class names) of type string.
Mentioned typings-for-css-loader contains a bug and because of types file generation delay, it's best to declare global *.css type in case our *.css.d.ts file is not generated yet.
That little bug scenario:
- Create css file
component.css - Include it in component
import * as css from './component.css' - Run
webpack - Typescript compiler will try to compile code (ERROR)
- Loader will generate Css modules typings file (
component.css.d.ts), but it's late for typescript compiler to find new typings file - Run
webpackagain will fix build error.
Easy fix is to create global definition (eg. file called typings.d.ts in your source root) for importing CSS Modules:
declare module '*.css' {
interface IClassNames {
[className: string]: string
}
const classNames: IClassNames;
export = classNames;
}
This definition will be used if there is no css file generated (eg. you have added new css file). Otherwise will be used generated specific (needs to be in same folder and named same as source file + .d.ts extension), eg. component.css.d.ts definition and IntelliSense will work perfectly.
Example of component.css.d.ts:
export const wrapper: string;
export const button: string;
export const link: string;
And if you don't want to see generated css typings you may setup filter in IDE to hide all files with extension .css.d.ts in your sources.
You cannot directly import CSS or any other static files into typescript using only the typescript compiler, but you can with the help of some build tools...
For example using webpack, you can set up the css-loader and style-loader to search your source code for require('./whatever.css') and add it to the build before safely compiling your typescript. If you also have webpack generate your HTML then your CSS will be automatically injected as a stylesheet.
See this answer:
https://stackoverflow.com/a/37144690/3850405
If you only need css for a class in your component you could do it like below. I like this solution for when inline css does not work and only small changes are needed.
import * as React from "react";
import { Header } from "./header";
export class Home extends React.Component<{}, {}> {
render() {
const css = `
.landing-page {
background-color: orange;
}
`
return (
<div>
<style>
{css}
</style>
<div id="page-top" className="landing-page">
<Header />
</div>
</div>
);
}
}