Angular 2 external style doesn't get inlined to header

后端 未结 3 398
遥遥无期
遥遥无期 2020-12-11 21:24

I have this component definition in typescript:

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

@Component({
    selector: \'my-app\',
    tem         


        
相关标签:
3条回答
  • 2020-12-11 21:57

    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.

    0 讨论(0)
  • 2020-12-11 21:59

    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

    0 讨论(0)
  • 2020-12-11 22:01

    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 {
    
    }
    
    0 讨论(0)
提交回复
热议问题