2016-05-19 3 views
2

Как использовать библиотеку компонентов Bootstrap (или любой другой)? Christopher · 6 минут назадКак использовать ng2-бутстрап с угловым 2?

Может кто-нибудь помочь с примерами кодом о том, как включить бутстраповскую компоненту

Я пытаюсь использовать самозагрузки предупреждения. Я установил пакет NPM и добавили пакет как:

предупреждения-component.ts:

import {Component} from '@angular/core'; 
import {CORE_DIRECTIVES} from '@angular/common'; 
import { AlertComponent } from 'ng2-bootstrap/ng2-bootstrap'; 
@Component({ 
    selector: 'alert-demo', 
    template: ` 
    <alert *ngFor="let alert of alerts;let i = index" [type]="alert.type" dismissible="true" (close)="closeAlert(i)"> 
     {{ alert?.msg }} 
    </alert> 
    <alert dismissOnTimeout="3000">This alert will dismiss in 3s</alert> 
    <button type="button" class='btn btn-primary' (click)="addAlert()">Add Alert</button> 
    `, 
    directives: [AlertComponent, CORE_DIRECTIVES] 
}) 
export class AlertDemoComponent { 
    public alerts:Array<Object> = [ 
    { 
     type: 'danger', 
     msg: 'Oh snap! Change a few things up and try submitting again.' 
    }, 
    { 
     type: 'success', 
     msg: 'Well done! You successfully read this important alert message.', 
     closable: true 
    } 
    ]; 
    public closeAlert(i:number):void { 
    this.alerts.splice(i, 1); 
    } 
    public addAlert():void { 
    this.alerts.push({msg: 'Another alert!', type: 'warning', closable: true}); 
    } 
} 

app.component.ts

import { Component } from '@angular/core'; 
import { Routes, ROUTER_DIRECTIVES } from "@angular/router"; 
import { MessagesComponent } from "./messages/messages.component"; 
import { AuthenticationComponent } from "./auth/authentication.component"; 
import {NavBarComponent} from "./navbar.component" 
import {AlertDemoComponent} from "./alert.component" 
@Component({ 
    selector: 'my-app', 
    template: ` 
      <navbar></navbar> 
      <alert-demo></alert-demo> 
    `, 
    directives: [ROUTER_DIRECTIVES, NavBarComponent,AlertDemoComponent] 
}) 
@Routes([ 
    {path: '/', component: MessagesComponent}, 
    {path: '/auth', component: AuthenticationComponent} 
]) 
export class AppComponent {} 

systemjs.config.js

(function(global) { 

    // map tells the System loader where to look for things 
    var map = { 
     'app':      'js/app', // 'dist', 
     'rxjs':      'js/vendor/rxjs', 
     '@angular':     'js/vendor/@angular' 
    }; 

    // packages tells the System loader how to load when no filename and/or no extension 
    var packages = { 
     'app':      { main: 'boot.js', defaultExtension: 'js' }, 
     'rxjs':      { defaultExtension: 'js' }, 
     "node_modules/ng2-bootstrap": {defaultExtension: 'js'} 
    }; 

    var paths= { 
    "ng2-bootstrap/ng2-bootstrap": "node_modules/ng2-bootstrap/ng2-bootstrap" 
    } 


    var packageNames = [ 
     '@angular/common', 
     '@angular/compiler', 
     '@angular/core', 
     '@angular/http', 
     '@angular/platform-browser', 
     '@angular/platform-browser-dynamic', 
     '@angular/router', 
     '@angular/testing', 
     '@angular/upgrade', 
     'ng2-bootstrap' 
    ]; 

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } 
    packageNames.forEach(function(pkgName) { 
     packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; 
    }); 

    var config = { 
     map: map, 
     packages: packages, 
     paths: paths 
    }; 

    // filterSystemConfig - index.html's chance to modify config before we register it. 
    if (global.filterSystemConfig) { global.filterSystemConfig(config); } 

    System.config(config); 

})(this); 

Я получаю ошибку

"NetworkError: 404 Not Found - http://localhost:3000/ng2-bootstrap/ng2-bootstrap" 
ng2-bootstrap 
Error: patchProperty/desc.set/[email protected]://localhost:3000/js/vendor/zone.js/dist/zone.js:769:27 
Zone</ZoneDelegate</[email protected]://localhost:3000/js/vendor/zone.js/dist/zone.js:356:24 
Zone</Zone</[email protected]://localhost:3000/js/vendor/zone.js/dist/zone.js:256:29 
ZoneTask/[email protected]://localhost:3000/js/vendor/zone.js/dist/zone.js:423:29 
Error loading http://localhost:3000/ng2-bootstrap/ng2-bootstrap as "ng2-bootstrap/ng2-bootstrap" from http://localhost:3000/js/app/alert.component.js 

ответ

2

Если предположить, что у вас есть NG2-самозагрузки в ваших package.json зависимости:

"ng2-bootstrap": "^1.0.16", 

И что он установлен в вашем проект node_modules, вы должны убедиться, включить библиотеку ng2-bootstrap в ваш index.html:

<script src="node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js"></script> 


После того как вы это, вы должны удалить его из вашего packageNames в systemjs.config.js:

var packageNames = [ 
     '@angular/common', 
     '@angular/compiler', 
     '@angular/core', 
     '@angular/http', 
     '@angular/platform-browser', 
     '@angular/platform-browser-dynamic', 
     '@angular/router', 
     '@angular/testing', 
     '@angular/upgrade' 
    ]; 


Кроме того, NG2-самозагрузка имеет зависимость от moment.js означает, что вы необходимо также включить его в ваши зависимости:

"moment": "^2.13.0" 

И вы, урожденная d, чтобы обновить systemjs.config.js содержать отображение:

var map = { 
     'app': 'app', // 'dist', 
     'rxjs': 'node_modules/rxjs', 
     'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 
     '@angular': 'node_modules/@angular', 
     moment: 'node_modules/moment/moment.js' 
    }; 

После того как вы все это на месте, вы должны быть в состоянии использовать любой из компонентов NG2-бутстраповских без проблем.

+0

Если у меня есть сценарий загрузки в скрипте, во время производственного кода, как index.html ссылается на папку node_modules. мое предположение заключалось в том, что мы не включаем node_modules в папку развертывания окончательной версии. исправьте, если ошибаетесь. В качестве альтернативы я наткнулся на использование gulp, чтобы фактически взять те файлы node_modules REQUIRED и поместить их в отдельную папку, которая будет использоваться в live env. – erchristopher

0

systemjs.конфиг

(function(global) { 

     // map tells the System loader where to look for things 
     var map = { 
      'app':      'js/app', // 'dist', 
      'rxjs':      'js/vendor/rxjs', 
      '@angular':     'js/vendor/@angular', 
      'moment':      'js/vendor/moment/moment.js', 
      'ng2-bootstrap':    'js/vendor/ng2-bootstrap' 
     }; 

     // packages tells the System loader how to load when no filename and/or no extension 
     var packages = { 
      'app':      { main: 'boot.js', defaultExtension: 'js' }, 
      'rxjs':      { defaultExtension: 'js' }, 
      'ng2-bootstrap':    { defaultExtension: 'js' } 
     }; 

     var packageNames = [ 
      '@angular/common', 
      '@angular/compiler', 
      '@angular/core', 
      '@angular/http', 
      '@angular/platform-browser', 
      '@angular/platform-browser-dynamic', 
      '@angular/router', 
      '@angular/testing', 
      '@angular/upgrade' 
     ]; 

     // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } 
     packageNames.forEach(function(pkgName) { 
      packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; 
     }); 

     var config = { 
      map: map, 
      packages: packages 
    }; 
// filterSystemConfig - index.html's chance to modify config before we register it. 
     if (global.filterSystemConfig) { global.filterSystemConfig(config); } 

     System.config(config); 

    })(this); 

gulpfile

gulp.task('vendor', function() { 

    // Angular 2 Framework 
    gulp.src('node_modules/@angular/**') 
     .pipe(gulp.dest(vendor + '/@angular')); 

    //ES6 Shim 
    gulp.src('node_modules/es6-shim/**') 
     .pipe(gulp.dest(vendor + '/es6-shim/')); 

    //reflect metadata 
    gulp.src('node_modules/reflect-metadata/**') 
     .pipe(gulp.dest(vendor + '/reflect-metadata/')); 

    //rxjs 
    gulp.src('node_modules/rxjs/**') 
     .pipe(gulp.dest(vendor + '/rxjs/')); 

    //systemjs 
    gulp.src('node_modules/systemjs/**') 
     .pipe(gulp.dest(vendor + '/systemjs/')); 

    //bootstrap 
    gulp.src('node_modules/ng2-bootstrap/**') 
     .pipe(gulp.dest(vendor + '/ng2-bootstrap')); 

    //moment.js for bootstrap datepicker 
    gulp.src('node_modules/moment/**') 
      .pipe(gulp.dest(vendor + '/moment')); 

    //zonejs 
    return gulp.src('node_modules/zone.js/**') 
     .pipe(gulp.dest(vendor + '/zone.js/')); 
}); 
0

Только в случае, если кто-то испытывает дополнительные проблемы и получаю эту ошибку:

Uncaught TypeError: System.registerDynamic is not a function. 

Решение: Переместите NG2-загрузочный скрипт тега после вашего тега сценария systemjs в файле index.html. Это не имеет значения, но сейчас это происходит.

Итак, если вы используете Angular2-quickstart, ваш index.html должен выглядеть так.

<html> 
    <head> 
    <title>Angular 2 QuickStart</title> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="styles.css"> 
    <!-- 1. Load libraries --> 
    <!-- Polyfill(s) for older browsers --> 
    <script src="node_modules/core-js/client/shim.min.js"></script> 
    <script src="node_modules/zone.js/dist/zone.js"></script> 
    <script src="node_modules/reflect-metadata/Reflect.js"></script> 
    <script src="node_modules/systemjs/dist/system.src.js"></script> 
    <script src="node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js"></script> 
    <!-- 2. Configure SystemJS --> 
    <script src="systemjs.config.js"></script> 
    <script> 
     System.import('app').catch(function(err){ console.error(err); }); 
    </script> 
    </head> 
    <!-- 3. Display the application --> 
    <body> 
    <app>Loading...</app> 
    </body> 
</html> 
Смежные вопросы