Angular 2 external style doesn't get inlined to header

十年热恋 提交于 2020-01-09 11:41:35

问题


I have this component definition in typescript:

import {Component, ViewEncapsulation} from 'angular2/core';

@Component({
    selector: 'my-app',
    templateUrl: '/views/sandbox.html',
    styleUrls: ['/styles/sandbox.css'],
    styles: [`.wow { background-color: red; }`],
    encapsulation: ViewEncapsulation.Emulated
})
export class SandBox { }

According to this article: http://blog.thoughtram.io/angular/2015/06/25/styling-angular-2-components.html both the style in the styles section and in the external stylesheet should be inlined into the header by angular.

Unfortunately, the second does not get injected, angular injects only the one in the styles section.

I have tried accessing /styles/sandbox.css from browser, it is fine. Angular is also able to access /views/sandbox.html so i have no idea why it is not happening.

I am using: "angular2": "2.0.0-beta.2" (latest beta AFAIK)


回答1:


I made some tests and strangely styles from the sandbox.css only applies if you use a relative paths within the styleUrls attribute:

@Component({
  selector: 'my-app',
  templateUrl: '/views/sandbox.html',
  styleUrls: ['../styles/sandbox.css'],
  styles: [`.wow { background-color: red; }`],
  encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent {
  constructor() {
  }
}

Edit

After having a look at the source code, Angular2 prevents from using absolute path for the styleUrls. See this line:

  • https://github.com/angular/angular/blob/master/modules/angular2/src/compiler/style_url_resolver.ts#L12

    export function isStyleUrlResolvable(url: string): boolean {
      if (isBlank(url) || url.length === 0 || url[0] == '/') return false; // <-----
      var schemeMatch = RegExpWrapper.firstMatch(_urlWithSchemaRe, url);
      return isBlank(schemeMatch) || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
    }
    

Hope it helps you, Thierry




回答2:


The Best way to fix this is use another css file for your component and add it to your StyleUrls list. Cleaner and will scale as you components grow.




回答3:


You can use systemjs and commonjs module dependencies loader, to load templates, styles and other files.

in commonjs moduleId : module.id in systemJs __moduleName

import {Component} from '@angular/core';

@Component({

moduleId:module.id,
selector: "exf-header",
templateUrl: "header.html",
styleUrls:['header.css']

})

export class HeaderComponent {

}


来源:https://stackoverflow.com/questions/35188803/angular-2-external-style-doesnt-get-inlined-to-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!