【问题标题】:styleUrls - Not able to load the css style sheet for the component using relative path in angular 2styleUrls - 无法使用角度 2 中的相对路径加载组件的 css 样式表
【发布时间】:2019-07-10 15:36:21
【问题描述】:

我在 Angular 2 的“app/Hero”下定义了一个“Hero”组件。英雄组件定义为“hero.component.html”、“hero.component.css”和“hero.component.ts”文件. templateUrl 工作正常,但 styleUrls 不加载。将显示资源未找到错误。我引用了这个链接 https://angular.io/docs/ts/latest/guide/component-styles.html#!#relative-urls 来使用相对 URL 加载样式。

  @Component({
  providers: [HeroService],
  templateUrl: './Hero.component.html',
  styleUrls: ['./Hero.component.css'],
})

【问题讨论】:

  • 去掉逗号。 css'],Hero 使用小写
  • 请在文件夹结构中添加文件名
  • @kimy82 我删除了最后一个逗号。但我仍然收到错误:加载资源失败。
  • 是的,我认为您可能必须设置选择器 selector: 'hero-component', 并将提供程序移动到 app.module.ts 。确保你没有使用 less 而不是 css 文件

标签: css angular typescript angular-components


【解决方案1】:

检查文件名并确保输入正确。它可能区分大小写!还要确保遵循正确的文件夹结构。

如果您的组件声明中有以下内容

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css'],
})

您的文件夹层次结构应如下所示:

app.module.ts
hero
- hero.component.ts
- hero.component.css
- hero.component.html

【讨论】:

  • @user1731770 我使用适合我的示例文件夹结构编辑了解决方案。现在可以用了吗?
  • 我有相同的文件夹结构。它显示相同的错误。加载资源失败。我没有在组件中提到选择器。
  • @user1731770 它当然不仅适用于绝对路径。选择器不相关。尝试使用 angular-cli 创建项目。它将以这种方式定义,并且文件夹结构和组件设置都将完美设置。
  • 我知道这听起来很疯狂。但我有一个 Ionic/Angular 2 项目,似乎绝对路径正在工作:(
【解决方案2】:

这对我有用:

styles: [require('./app.component.css').toString()]

而且你必须更改 webpack.config.js。您必须指定下一个,而不是“raw-loader”:

loader: 'style-loader!css-loader'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 2019-02-09
    • 1970-01-01
    • 2016-07-31
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多