Andrew Willems Andrew Willems - 3 months ago 9
CSS Question

How do I mix "absolute" and relative urls in Angular2?

There are (at least?) 2 ways of specifying urls for the

templateUrl
and
styleUrls
properties of Component decorators in Angular2:


  1. "absolute" or, more precisely, relative to the project root (the default), and

  2. relative to the current document/component.



The latter is accomplished by using component-relative paths, i.e. by including
moduleId: module.id
in the decorator.

But how do I combine the two? For example, I want to use two different style files for one component:


  1. one that is used generally for my whole project


    • my-general-project-styles.css
      in the example below

    • file location should be relative to the project root (e.g. directly in the project root) so that many files in different locations can access it in its central location


  2. one that is specific for my current component


    • my-specific-component.styles.css
      in the example below

    • file location should be relative to the current file/component so that the file and its associated styles (and templates, etc.) can be moved around easily




e.g.:

@Component({
moduleId: module.id, // I'm not sure if I should still use this
template: '<h1>My Component</h1>',
styleUrls: ['my-general-project-styles.css', 'my-specific-component-styles.css']
})
export class MyComponent {}


By the way, I'm using the commonjs module.

Answer

Turned out to be simpler than I expected...just put a '/' in front of the url that you want to be relative to the project root, e.g.

@Component({
    moduleId: module.id,
    template: '<h1>My Component</h1>',
    styleUrls: ['/my-general-project-styles.css', 'my-specific-component-styles.css']
})
export class MyComponent {}
Comments