首页 文章

如何在Angular v2组件中添加样式URL?

提问于
浏览
0

我在他们的网站上关注Angular教程,并创建了一些组件,模板和样式 .

我在使用'@Component'装饰器的'styleURLs'属性在组件中包含我的样式时遇到问题 . 这就是我的意思,

@Component({
  selector: 'curries',
  templateUrl: '../Views/curries.component.html',
  styleUrls: ['../../../assets/styles/curries.component.css'],
  providers: [CurryService]
})
export class CurriesComponent { // blah blah

可以看出,我把我的样式放在'assets / styles'文件夹中 .

这是我的文件夹结构,

/src
    /app
        /Views
        /Components
           /curries.component.ts
        /Services
        /Models
    /assets
        /images
        /styles
           -curries.component.css

我想知道这是否可能;将样式文档放在不同的文件夹中并在组件中引用它 .

我只是想在app目录中解压缩我的文件,并且在某处读取图像和样式需要位于'assets'文件夹(这是'Content'文件夹,因此它有意义)

任何帮助表示赞赏:)

附:这是我构建应用程序时遇到的错误

ERROR in ./src/app/Components/curries.component.ts
Module not found: Error: Can't resolve 
'../../../assets/styles/curries.component.css' in             
'~\AngularProjects\HelloWorld\src\app\Components'

resolve '../../../assets/styles/curries.component.css' in 
'~\AngularProjects\HelloWorld\src\app\Components'using 
 description file: ~\AngularProjects\HelloWorld\package.json (relative 
 path: ./src/app/Components)

3 回答

  • 1

    我认为你过度引用了1级 . 所以它应该是 ../../assets...

    话虽如此,我认为将组件特定样式与组件文件保持在一起通常是“最佳实践” .

    而不是通过视图/组件/服务/模型分解,而是按组件分解 . 我们一般都有类似的东西:

    /src
        /app
            /compoenents
                /curries
                    curries.component.ts
                    curries.component.css
                    curries.component.html
            /shared
                { put and shared modules here }
        /assets
            /images 
            /styles
                { global styles go here }
    

    https://angular.io/guide/styleguide有很多关于此的信息 .

  • 0

    是的,您可以访问styleUrls数组中的任何样式

    https://angular.io/guide/component-styles#style-urls-in-metadata

    有关在不同路径中引用其他.css文件的一个很好的示例,请参阅此Plunker

    @Component({
      selector: 'my-app',
      template: `
        <h1>Title</h1>
        <p>Hello...</p>
        <span>... world!</span>`,
      styleUrls: [
        'app/app1.component.css',
        'testing/app2.component.css'
      ]
    })
    
  • 0

    引用(对于模板url的样式)是 relative 到"Index.html"你的主html页面 .

相关问题