如何在Angular 2中使用ng2-bootstrap?

时间:2016-05-19 14:23:50

标签: angular ng2-bootstrap

如何使用Bootstrap(或任何其他)组件库? 克里斯托弗·6分钟前

任何人都可以帮助获取有关如何包含引导程序组件的示例代码

我正在尝试使用引导警报。我安装了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/wrapFn@http://localhost:3000/js/vendor/zone.js/dist/zone.js:769:27
Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:3000/js/vendor/zone.js/dist/zone.js:356:24
Zone</Zone</Zone.prototype.runTask@http://localhost:3000/js/vendor/zone.js/dist/zone.js:256:29
ZoneTask/this.invoke@http://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

3 个答案:

答案 0 :(得分:2)

假设您的package.json依赖项中有 ng2-bootstrap

"ng2-bootstrap": "^1.0.16",

并且它已安装在项目的node_modules中,您需要确保在index.html中包含ng2-bootstrap库:

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


完成此操作后,您应该将其从systemjs.config.js中的 packageNames 中删除:

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依赖于 moment.js ,这意味着您还需要将它包含在依赖项中:

"moment": "^2.13.0"

您需要更新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-bootstrap组件。

答案 1 :(得分:0)

<强> systemjs.config

    (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/'));
});

答案 2 :(得分:0)

以防其他人遇到其他问题并收到此错误:

<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>

解决方案:在index.html文件中的systemjs脚本标记之后移动ng2-bootstrap脚本标记。这应该不重要,但现在它确实如此。

因此,如果您使用的是Angular2-quickstart,则index.html应该如下所示。

GET http://localhost:8080/amitopticals/debug/default/toolbar?tag=57a4b1623a201

200 OK
        90ms    
create (line 545)
GET http://localhost:8080/amitopticals/orders/orders/....php?r=orders/customer/get-for-customer&custid=2

404 Not Found
        10ms    
jquery.js (line 9175)
ParamsHeadersResponseHTMLCookies

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Object not found!</title>
<link rev="made" href="mailto:postmaster@localhost" />
<style type="text/css"><!--/*--><![CDATA[/*><!--*/ 
    body { color: #000000; background-color: #FFFFFF; }
    a:link { color: #0000CC; }
    p, address {margin-left: 3em;}
    span {font-size: smaller;}
/*]]>*/--></style>
</head>

<body>
<h1>Object not found!</h1>
<p>


    The requested URL was not found on this server.



    The link on the
    <a href="http://localhost:8080/amitopticals/orders/orders/create">referring
    page</a> seems to be wrong or outdated. Please inform the author of
    <a href="http://localhost:8080/amitopticals/orders/orders/create">that page</a>
    about the error.



</p>
<p>
If you think this is a server error, please contact
the <a href="mailto:postmaster@localhost">webmaster</a>.

</p>

<h2>Error 404</h2>
<address>
  <a href="/">localhost</a><br />
  <span>Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12</span>
</address>
</body>
</html>