development

Angular 프로젝트에서 부트 스트랩을 사용하는 방법은 무엇입니까?

big-blog 2020. 5. 28. 19:12
반응형

Angular 프로젝트에서 부트 스트랩을 사용하는 방법은 무엇입니까?


첫 번째 Angular 응용 프로그램을 시작 하고 기본 설정이 완료되었습니다.

애플리케이션 부트 스트랩추가 하려면 어떻게 해야합니까?

예제를 제공 할 수 있다면 큰 도움이 될 것입니다.


당신이 사용 제공 각도-CLI를 새로운 프로젝트를 생성하기 위해,에서 액세스 할 수 부트 스트랩 할 수있는 또 다른 방법이 각도 2/4 .

  1. 명령 행 인터페이스를 통해 프로젝트 폴더로 이동하십시오. 그런 다음 npm사용 하여 부트 스트랩을 설치하십시오
    $ npm install --save bootstrap. --save옵션은 부트 스트랩을 종속성에 표시합니다.
  2. 프로젝트를 구성하는 .angular-cli.json 파일을 편집하십시오. 프로젝트 디렉토리 안에 있습니다. "styles"배열에 대한 참조를 추가하십시오 . 참조는 npm으로 다운로드 한 부트 스트랩 파일의 상대 경로 여야합니다. 제 경우에는 :"../node_modules/bootstrap/dist/css/bootstrap.min.css",

내 예 .angular-cli.json :

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "bootstrap-test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

이제 부트 스트랩이 기본 설정의 일부 여야합니다.


Angular2와의 통합은 ng2-bootstrap 프로젝트 ( https://github.com/valor-software/ng2-bootstrap )를 통해서도 가능합니다 .

설치하려면 다음 파일을 기본 HTML 페이지에 넣으십시오.

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

그런 다음 다음과 같이 구성 요소에 사용할 수 있습니다.

import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'my-app',
  directives: [Alert],
  template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}

index.html 파일 내에 boostrap CSS를 포함시키기 만하면됩니다.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

또 다른 좋은 (더 나은) 대안은 angular-ui 팀이 만든 일련의 위젯을 사용하는 것입니다 : https://ng-bootstrap.github.io


이 스레드에서 언급 된 angular-ui 팀의 ng-bootstrap에 필요한 Bootstrap 4 를 사용하려는 경우 대신 이것을 사용하는 것이 좋습니다 (참고 : JS 파일을 포함하지 않아도 됨).

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

SASS를 사용한다고 가정 npm install bootstrap@4.0.0-alpha.6 --save하고 파일에서 파일을 가리켜 실행 후에 로컬로이를 참조 할 수 있습니다 styles.scss.

@import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';

가장 인기있는 옵션은 ng2-bootstrap 프로젝트 https://github.com/valor-software/ng2-bootstrap 또는 Angular UI Bootstrap 라이브러리 와 같은 npm 패키지로 배포 된 타사 라이브러리를 사용하는 것 입니다.

개인적으로 ng2-bootstrap을 사용합니다. 구성은 Angular 프로젝트의 빌드 방법에 따라 다르므로 구성하는 방법에는 여러 가지가 있습니다. 아래에 Angular 2 QuickStart 프로젝트를 기반으로 한 예제 구성 게시 https://github.com/angular/quickstart

먼저 패키지에 의존성을 추가합니다.

    { ...
"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",

    ...

    "bootstrap": "^3.3.7",
    "ng2-bootstrap": "1.1.16-11"
  },
... }

그런 다음 systemjs.config.js에서 이름을 올바른 URL로 매핑해야합니다.

(function (global) {
  System.config({
    ...
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      //bootstrap
      'moment': 'npm:moment/bundles/moment.umd.js',
      'ng2-bootstrap': 'npm:ng2-bootstrap/bundles/ng2-bootstrap.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
...
  });
})(this);

부트 스트랩 .css 파일을 index.html로 가져와야합니다. 부트 스트랩 3.3.7 의존성을 추가했기 때문에 하드 드라이브의 / node_modules / bootstrap 디렉토리 또는 웹에서 가져올 수 있습니다. 우리는 웹에서 그것을 얻고 있습니다 :

<!DOCTYPE html>
<html>
  <head>
    ...
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    ...
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

/ app 디렉토리에서 app.module.ts 파일을 편집해야합니다

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

//bootstrap alert import part 1
import {AlertModule} from 'ng2-bootstrap';

import { AppComponent }  from './app.component';


@NgModule({
  //bootstrap alert import part 2
  imports:      [ BrowserModule, AlertModule.forRoot() ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

마지막으로 / app 디렉토리의 app.component.ts 파일

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

@Component({
    selector: 'my-app',
    template: `
    <alert type="success">
        Well done!
    </alert>
    `
})

export class AppComponent {

    constructor() { }

}

그런 다음 앱을 실행하기 전에 부트 스트랩과 ng2-bootstrap 종속성을 설치해야합니다. 프로젝트 디렉토리로 이동하여 다음을 입력하십시오.

npm install

마지막으로 앱을 시작할 수 있습니다

npm start

ng2-bootstrap 프로젝트 github에는 다양한 Angular 2 프로젝트 빌드로 ng2-bootstrap을 가져 오는 방법을 보여주는 많은 코드 샘플이 있습니다. plnkr 샘플도 있습니다. Valor-software (라이브러리 작성자) 웹 사이트에도 API 설명서가 있습니다.


앵귤러 클리 환경에서 내가 찾은 가장 간단한 방법은 다음과 같습니다.


1. s̲c̲s̲s̲ 스타일 시트가있는 환경에서의 솔루션

npm install bootstrap-sass —save

style.scss에서 :

$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

참고 1 :이 ~문자는 nodes_modules 폴더에 대한 참조 입니다.
참고 2 : scss를 사용함에 따라 원하는 모든 boostrap 변수를 사용자 정의 할 수 있습니다.


2. c̲s̲s̲ 스타일 시트가있는 환경에서의 솔루션

npm install bootstrap —save

style.css에서 :

@import '~bootstrap/dist/css/bootstrap.css';

There are several ways to configure angular2 with Bootstrap, one of the most complete ways to get the most of it is to use ng-bootstrap, using this configuration we give to algular2 complete control over our DOM, avoiding the need to use JQuery and Boostrap.js.

1-Take as a starting point a new project created with Angular-CLI and using the command line, install ng-bootstrap:

npm install @ng-bootstrap/ng-bootstrap --save

Note: More info at https://ng-bootstrap.github.io/#/getting-started

2-Then we need to install bootstrap for the css and the grid system.

npm install bootstrap@4.0.0-beta.2 --save

Note: More info at https://getbootstrap.com/docs/4.0/getting-started/download/

Now we have the setup the environment and for that we have to change the .angular-cli.json adding to the style:

"../node_modules/bootstrap/dist/css/bootstrap.min.css"

Here is an example:

"apps": [
    {
      "root": "src",
        ...
      ],
      "index": "index.html",
       ...
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]

The next step is to add the ng-boostrap module to our project, to do so we need to add on the app.module.ts:

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

Then add the new module to the application app: NgbModule.forRoot()

Example:

@NgModule({
  declarations: [
    AppComponent,
    AppNavbarComponent
  ],
  imports: [
    BrowserModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Now we can start using bootstrap4 on our angular2/5 project.


I had the same question and found this article with a really clean solution:

http://leon.radley.se/2017/01/angular-cli-and-bootstrap-4/

Here are the instructions, but with my simplified solution:

Install Bootstrap 4 (instructions):

npm install --save bootstrap@4.0.0-alpha.6

If needed, rename your src/styles.css to styles.scss and update .angular-cli.json to reflect the change:

"styles": [
  "styles.scss"
],

Then add this line to styles.scss:

@import '~bootstrap/scss/bootstrap';

just check your package.json file and add dependencies for bootstrap

"dependencies": {

   "bootstrap": "^3.3.7",
}

then add below code on .angular-cli.json file

 "styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.css"
  ],

Finally you just update your npm locally by using terminal

$ npm update

  1. npm install --save bootstrap
  2. go to -> angular-cli.json file, find styles properties and just add next sting: "../node_modules/bootstrap/dist/css/bootstrap.min.css", It might be looks like this:

    "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
    ],
    

Procedure with Angular 6+ & Bootstrap 4+ :

  1. Open a shell on the folder of your project
  2. Install bootstrap with the command : npm install --save bootstrap@4.1.3
  3. Bootstrap need the dependency jquery, so if you don't have it, you can install it with the command : npm install --save jquery 1.9.1
  4. You may need to fix vulnerability with the command : npm audit fix
  5. In your main style.scss file, add the following line : @import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

OR

Add this line to your main index.html file : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


I was looking for same answer and finally I found this link. You can find explained three different ways how to add bootstrap css into your angular 2 project. It helped me.

Here is the link: http://codingthesmartway.com/using-bootstrap-with-angular/


You can try to use Prettyfox UI library http://ng.prettyfox.org

This library use bootstrap 4 styles and not need jquery.


add the following lines in your html page

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

If you use angular cli, after adding bootstrap into package.json and install the package, all you need is add boostrap.min.css into .angular-cli.json's "styles" section.

One important thing is "When you make changes to .angular-cli.json you will need to re-start ng serve to pick up configuration changes."

Ref:

https://github.com/angular/angular-cli/wiki/stories-include-bootstrap


Another very good alternative is to use the skeleton Angular 2/4 + Bootstrap 4

1) Download ZIP and extract zip folder

2) ng serve


My recommendation would be instead of declaring it in the json stylus to put it in the scss so that everything is compiled and in one place.

1)install bootstrap with npm

 npm install bootstrap

2) Declare bootstrap npm in the css with our styles

Create _bootstrap-custom.scss:

  // Required
  @import "bootstrap-custom-required";


  // Optional
  @import "~bootstrap/scss/root";
  @import "~bootstrap/scss/grid";
  @import "~bootstrap/scss/tables";

    ...
    ..
    .

3) Within the styles.scss we insert

@import "bootstrap-custom";

so we will have all our core compiled and in one place

참고URL : https://stackoverflow.com/questions/36292438/how-to-use-bootstrap-in-an-angular-project

반응형