2

I'd like to get the CSS file content of a component.

For example:

hello-world.component.ts:

@Component({
    selector: 'app-hello-world',
    template: `<h1>Hello World</h1>`,
    styleUrls: ['./hello-world.component.css']
})

export class HelloWorldComponent {
    getCSSContent(){
    }
}

hello-world.component.css:

h1 {
    color: red;
    font-weight: 400;
}

I expect getCSSContent function to return:

h1 {
    color: red;
    font-weight: 400;
}
2
  • try something like this: this.http.get('./app.component.css').subscribe(data => { console.log('data', data); }) (http request with httpClient) Commented May 1, 2019 at 9:57
  • You can't get the CSS at run-time. You can't access the original CSS source code or find the <script> tag created by Angular. What I did, was to make a copy of the CSS file to my /assets/ folder and read it from there. Commented May 1, 2019 at 20:28

1 Answer 1

4

In the folder 'src' add a new file with following name:

typings.d.ts

with the following content:

declare module '*.css';

In your component add:

import helloWorldCss from './hello-world.component.css'

and you can read your css with

getCSSContent(){
    return helloWorldCss;
}

I recognized some weird text at the end of the helloWorldCss variable.. maybe you have to trim it.

Sign up to request clarification or add additional context in comments.

4 Comments

This will not work. helloWorldCss will be the WebPack module that was created at compile time. I know, because I tried this same thing last week. :)
are you sure? I tested it with ng serve and with publishing it with IIS and it is working..
I was using a raw-loader at the time. Maybe that changed how imports are handled. stackoverflow.com/questions/55714565/…
you saved my day! this is the second time your answer helped me. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.