2
votes

I am running my front-end application using the Angular-Cli.

I want to add a css file from the node_module only to that specific component. I do not want to add the CSS file to the Angular.cli.json "scripts": [] array,

I have the following component:

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

@Component({  
    selector: 'fbsign-component',
    templateUrl: './fb.signin.component.html',

    styleUrls: ['./fb.signin.component.css', '../../node_modules/bootstrap-social/bootstrap-social.css'] })

export class FbSigninComponent{

    constructor(){}

    ngOnInit(): any{}

    onClick(){
        window.location.href ="http://localhost:1337/facebook"
    }
}

I think that the something is blocking the styleURLs[] from accessing the CSS files located in node_module directory.

How do I unblock it?

4

4 Answers

1
votes

Try like this :

the below home.component.ts file is following the location in my project

src => app => home

here my home.component.ts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css', '../../../node_modules/bootstrap/dist/css/bootstrap.css']
})
1
votes

Well you can load it dynamically.

ngOnInit() 
{
    this.loadStyle('your path');
 } 

     loadStyle(src)
  {
  let link = document.createElement('link');
  link.href = src;
  link.rel = 'stylesheet';
  link.type = 'text/css';
let head = document.getElementsByTagName('head')[0];
  let links = head.getElementsByTagName('link');
  let style = head.getElementsByTagName('style')[0];
  head.insertBefore(link, style);
  }
1
votes

maybe you need to use ViewEncapsulation.None in order to make this component accessible for the styles from node modules. Try add this to your component decorator:

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

@Component({  
    selector: 'fbsign-component',
    templateUrl: './fb.signin.component.html',
    styleUrls: [
        './fb.signin.component.css',
        '../../node_modules/bootstrap-social/bootstrap-social.css'
    ],
    encapsulation: ViewEncapsulation.None
})

export class FbSigninComponent{
}

another option is to add these external styles into angular.json: architect->build->options

"options": [
    ...
    "styles": [
        "./node_modules/bootstrap-social/bootstrap-social.css",
        "src/styles.scss"
    ]
]
0
votes

Is your directory structure correct? To access files, outside your current folder, use "../"

Another reason might be that you are trying to access styles inside a child component while they should be inserted in the parent component where the component is injected using the selector, to get the proper layout.

So, try adding the styles to the component where you are using 'fbsign-component' as a selector.