简体   繁体   中英

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 am 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 this @import "bootstrap/dist/css/bootstrap.css"; in css file but did not help.

TIA:)

I'm late to the party but I encountered this problem not so long ago: the need of using Bootstrap styles in only one component.
To solve this, I went to the Bootstrap website and downloaded the compiled CSS files. I was only interested in the bootstrap.min.css file. To load it in only one component, actually the top header of the web page (I needed to get up and running quickly with a collapbsable navbar), I added the file mentioned above in the stylesUrl prop. of my 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, I can use all Bootstrap styles in the top section of my web app' and in this place only:)

Bear in mind though that even the minified Boostrap style sheet will raise an error if you didnt 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 suits your needs, you will be interested in particular in 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"
                }
              ]
    ...

My trivial solution would be to insert the content of the bootstrap file to component CSS file, but this is only my opinion, not sure is it right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM