Ways to incorporate style links in Angular v2 components?

Currently, I am working through the Angular tutorial available on their website. In my quest to create various components, templates, and styles, I have hit a roadblock.

The issue lies in incorporating my styles into the components using the 'styleURLs' property of the '@Component' decorator. Here's a snippet of what I've attempted:

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

My attempt has been to place the styles within the 'assets/styles' folder, as illustrated above.

A glimpse at my current folder structure reveals:

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

One query that continues to bother me is whether it's feasible to house style documents in a separate folder and then reference them in the component.

This move is primarily driven by my desire to keep the files within the app directory organized. Besides, I stumbled upon suggestions indicating that images and styles ought to reside in the 'assets' folder for better structuring purposes.

Any assistance or guidance on this matter would be greatly appreciated :)

Psst! An error message pops up whenever I try to build the app:

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)

Answer №1

It seems like you may have dereferenced one level too far. The correct path should be ../../assets...

However, I personally believe that it is considered a "best practice" to store component-specific styles with the respective component files.

Rather than organizing your code by view/component/service/model, consider organizing it by component. For example:

/src
    /app
        /components
            /curries
                curries.component.ts
                curries.component.css
                curries.component.html
        /shared
            {place shared modules here}
    /assets
        /images 
        /styles
            {store global styles here}

For more information on this topic, refer to https://angular.io/guide/styleguide.

Answer №2

When it comes to the references for styles of template URLs, they are actually relative to your main HTML page, which is typically named "Index.html".

Answer №3

Absolutely, you have the ability to access any style specified within the styleUrls array

For more information, visit: https://angular.io/guide/component-styles#style-urls-in-metadata

If you need a practical example, check out this Plunker website that demonstrates how to reference other .css files located in various paths

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

What could be causing the image to vanish when combining a condition with 'linear-gradient' as the value for 'background-image'?

If the variable effect is set to true, I want to display the linear-gradient effect, otherwise only show the image. picture = 'https://i.blogs.es/7c43cd/elon-musk-no-queria-ser-ceo-e-hizo-todo-lo-posible-para-evitarlo-pero-asegura-que-sin-el-tesla-mo ...

How can I disable the background color in Chrome autocomplete? Is there a way to make the background

There's a form on my website where the autocomplete feature shows a blue background color. The form itself has a semi-transparent white background. I managed to change the autofill color to white using this CSS property: -webkit-box-shadow: 0 ...

Searching through all values can be done by following these steps

Need help with implementing a search feature that can search all values in Angular2. Here's the current code snippet: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Angular2 marker with custom design for Google Maps

We have successfully implemented Angular2 Google Maps () and integrated Styled Google Maps using the following Plunkr: https://plnkr.co/edit/rv6udUOEedMxJejEpIW1 import { Directive } from '@angular/core'; import { GoogleMapsAPIWrapper } from &a ...

Adjust the width of the <td> elements that are nested under <th> elements with a specified

I want to define the width of the td elements in the tbody section under a thead element with colspan="2" using specific column widths in %. I need the table to maintain a fixed width without dynamically adjusting based on content. .sample { width: 10 ...

What is the process for appending an attribute to a DOM element?

Is there a way to conditionally add the multiple attribute to this element? <mat-select [formControlName]="field.name" multiple> I attempted to do so with the following: <mat-select [formControlName]="field.name" [attr.multiple]="field?.mu ...

Dynamic Sizing of Inline Input Fields in Bootstrap 3 Using Narrow Columns

My goal is to create an inline form within a small container (.col-sm-4) without it wrapping into multiple lines. I want the inputs to adjust to the column size while also having the button in the desired position. To achieve this, I have managed to remove ...

Ways to check my component using ActivatedRoute?

I am currently facing an issue while testing a component that utilizes two resolvers (pagesResolver and UploadResolver): Below is the code snippet for my component: export class AdminPagesComponent implements OnInit { fileUploads$: Observable<FileUpl ...

Style the arrangement of table cells with CSS

Is there a way to minimize the space between the text "Name:" and "Bob", as well as between "Age:" and "20" using CSS? fiddle: http://jsfiddle.net/QfN3f/2/ html: <table class="table"> <tr class="table-row"> <td class="tabl ...

Position an element in the middle of the range between the tallest and shortest characters

Is there a way to vertically center an element between the tallest and shortest characters of another element (preferably using just CSS, but JavaScript is also acceptable)? I want it to be aligned with the actual text content rather than the line height, ...

New alternative for form-control-feedback in Bootstrap 4

The form-control-feedback class doesn't appear to be included in Bootstrap 4. What is the most effective way to achieve the desired outcome (an icon inside the textbox) using Bootstrap 4? <head> <link rel="stylesheet" href="https://max ...

Express and Angular2 Webpack integration

Recently, I set up Angular 2 with Webpack and explored its routing capabilities through a sample app. I am now interested in integrating Angular2 for front end routing while utilizing ExpressJS for a RESTful API backend on the same server. For example, ht ...

Mixing two elements for a continuous animation without the use of JavaScript

I'm interested in creating an animation that cycles between "0% interest free credit" and "free delivery". I am attempting to achieve this without the use of JavaScript, but so far I can only make the first element fade away without the second one fad ...

Hover over the image to reveal sliding text

I am attempting to incorporate a CSS3 hover effect into my images, where hovering over an image will cause some text to slide up on a white background. However, I have encountered issues with conflicting code, as I also have overlay text and a 'new&ap ...

Using getServerSideProps in Next.js is preventing the global css from loading

In my Next.js application, I have defined global styles in the file /styles/globals.css and imported them in _app.tsx. // import default style import "../styles/globals.css"; function MyApp({ Component, pageProps }) { return <Component {...pageProps ...

Simplifying the process of implementing Jquery CSS Toggles

I am planning to simplify the process of toggling visibility for 12 different divs when clicking on 12 different buttons. Instead of repeating the same code multiple times, I am considering a more efficient approach. My idea is to: Step A) Initially hide ...

What is the proper way to define a class attribute for an HTML element within a PHP file?

I am having trouble writing the class attribute in a PHP file for an HTML element. Here is my code: echo '<div><p class="'.($value->getIsRequire() == 1) ? 'required' : ''.'"> </p> <input type="tex ...