【问题标题】:How to get CSS file content of component in Angular 7?如何在 Angular 7 中获取组件的 CSS 文件内容?
【发布时间】:2019-09-19 21:43:45
【问题描述】:

我想获取一个组件的 CSS 文件内容。

例如:

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;
}

我希望 getCSSContent 函数返回:

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

【问题讨论】:

  • 尝试这样的事情:this.http.get('./app.component.css').subscribe(data =&gt; { console.log('data', data); })(使用 httpClient 的 http 请求)
  • 您无法在运行时获取 CSS。您无法访问原始 CSS 源代码或找到 Angular 创建的 &lt;script&gt; 标签。我所做的是将 CSS 文件复制到我的 /assets/ 文件夹并从那里读取。

标签: css angular angular7


【解决方案1】:

在文件夹'src'中添加一个具有以下名称的新文件:

typings.d.ts

内容如下:

declare module '*.css';

在你的组件中添加:

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

你可以阅读你的CSS

getCSSContent(){
    return helloWorldCss;
}

我在 helloWorldCss 变量的末尾发现了一些奇怪的文本。也许你必须修剪它。

【讨论】:

  • 这行不通。 helloWorldCss 将是在编译时创建的 WebPack 模块。我知道,因为我上周尝试了同样的事情。 :)
  • 你确定吗?我用 ng serve 测试它并用 IIS 发布它,它正在工作..
  • 当时我使用的是 raw-loader。也许这改变了进口的处理方式。 stackoverflow.com/questions/55714565/…
  • 你拯救了我的一天!这是您的回答第二次帮助我。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 2020-09-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
相关资源
最近更新 更多