How to use bootstrap in Angular
In this blog, I will explain 2 ways to apply
- Use ng-bootstrap
- Import general Bootstrap (css, js)
ng-bootstrap
ng-bootstrap is Bootstrap4 based prepared component. We can use several boostrap tips using ng-bootstrap tag.
Install dependencies
npm install --save @ng-bootstrap/ng-bootstrap npm install --save bootstrap
Let’s try Module
app.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ CommonModule, NgbModule, BrowserModule, FormsModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { }
Component Example
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <p> <ngb-alert [dismissible]="false"> <strong>Warning!</strong> Hahahaha! </ngb-alert> </p> ` }) export class AppComponent {}
Apply General bootstrap
Install boostrap
npm install --save bootstrap
We can install bootstrap under node_modules/bootstrap
Change default import style
See index.html. if you are creating app from angular-cli, you can see it.
If you add css link to this file, any css files are applied, of course bootstrap css file, too.
If you are using smart way,(dynamic import), we can use angular.json file.
Add following to angular.json, import css file dynamically (when compiling)
"styles": [ "node_modules/bootstrap/dist/css/bootstrap.css", "src/styles.css" ]
Use boostrap as usual in component
Component
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div> <button class="btn-primary btn">Bootstrap Button</button> </div> <br /> <div> <button class="btn btn-info">Bootstrap Button2</button> </div> ` }) export class AppComponent {}
コメント