Arokia Lijas
Arokia Lijas

Reputation: 543

How to use Bootstrap in only one component in Angular

I'm having an angular application with custom themes, most of the components don't require Bootstrap, so in my angular.json, I included only the bootstrap.grid.css.

As the application was developed, I became in need of Bootstrap, but including it in angular.json is affecting styling in other components.

Is there any option to use Bootstrap only in this particular component.

I tried @import "bootstrap/dist/css/bootstrap.css"; in the CSS file, but, it did not help.

Upvotes: 2

Views: 5252

Answers (1)

yactouat
yactouat

Reputation: 507

Download the compiled CSS files from the Bootstrap website, for example, the bootstrap.min.css file.

To load it in only one component, for example, the top header of the web page, add the file mentioned above in the stylesUrl prop of the component decorator like so (you are free to put the Bootstrap CSS file elsewhere):

import { Component } from '@angular/core';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: [
    "./../../../assets/css/bootstrap.min.css",
    "./header.component.css"
  ]
})
export class HeaderComponent {
  constructor() { }
}

Now, thanks to default view encapsulation, it's possible to use all Bootstrap styles in the top section of the web app, and in this place only.

Bear in mind, though, that even the minified Bootstrap style sheet will raise an error if you didn't modify your angular.json file the day you will run ng build --prod to deploy your app; the reason is that, by default, budgets for components' styles are set to a low maximum value for performance reasons.

So, in your angular.json, look for the budgets array, and in there, set a rule for your components styles that suit your needs. You will be interested in particular with the maximumError value, that might prevent you from doing your prod build if you load large style sheets in a given component:

...
          
"budgets": [
    {
        "type": "initial",
        "maximumWarning": "2mb",
        "maximumError": "5mb"
    },
    {
        "type": "anyComponentStyle",
        "maximumWarning": "6kb",
        "maximumError": "145kb"
    }
]
...

Upvotes: 6

Related Questions