简体   繁体   中英

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, ie 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 (eg 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

eg:

@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.

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, eg

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

The solution does not work for me. I use angular 2.0.3 - Any changes since your post?

Does not work:

@Component({
moduleId: module.id,
selector: "process-list",
templateUrl: "processList.component.html",
styleUrls: ["/Content/processList.css"]
})

Works:

@Component({
moduleId: module.id,
selector: "process-list",
templateUrl: "processList.component.html",
styleUrls: ["../../../Content/processList.css"]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM