Load css from a CDN in an Angular 2 Component

2019-06-21 04:04发布

问题:

As the title says, i want to include external css in an Angular 2 component. Here's how i am doing it now:

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

@Component({
    selector: 'app-auth',
    templateUrl: './auth.component.html',
    styleUrls: [
        'https://fonts.googleapis.com/css?family=Dosis:400,500,600,700',
        'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',
        './assets/css/bootstrap.min.css',
        './assets/css/main.css',
        './assets/css/responsive.css',
        './auth.component.css',
    ],
})
export class AuthComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }

}

The first two URLs don't work. I'm getting an error:

ncaught Error: Cannot find module "./https://fonts.googleapis.com/css?family=Dosis:400,500,600,700"

I can make it work by including it directly into the HTML, but i don't think that's the right way to do it.

Edit: I even tried using encapsulation: ViewEncapsulation.None, that didn't help.

回答1:

You should load only local styles in the array of styleUrls. Therefore, in auth.component.css, import your desired external stylesheets:

@import "https://fonts.googleapis.com/css?family=Dosis:400,500,600,700";
@import "http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css";


回答2:

In contrast with templateUrl It seems that styleUrls can only be defined relatively.

A solution to that problem would be to load your absolute external fonts or CSS dependencies from some css code and you could put this piece of css code inside @Component in the inline styles like this:

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

@Component({
    selector: 'app-auth',
    templateUrl: './auth.component.html',
    styles: ['
        @import "https://fonts.googleapis.com/css?family=Dosis:400,500,600,700";
        @import "http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css";
    '],
    styleUrls: [
        './assets/css/bootstrap.min.css',
        './assets/css/main.css',
        './assets/css/responsive.css',
        './auth.component.css'
    ],
})
export class AuthComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }

}

If you wish you can transfer your relative dependencies inside styles:[...] and load each of them with a @import. Note: while using the combination styles:[...] + styleUrls:[...] works fine, you can only use templateUrl:'...' or template:'...'