Search code examples
angularng2-bootstrap

Integrate ng2-bootstrap with Angular2


Been trying to integrate ng2-bootstrap with Angular2 beta.9 using CDN reference.

Non working plunker

index.html

 <script>
       System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {
          'src': {defaultExtension: 'ts'},
          'ng2-material': { defaultExtension: 'js' },
          'ng2-bootstrap':{defaultExtension: 'js'}
        },
        map: {
                'ng2-material': 'https://cdn.rawgit.com/justindujardin/ng2-material/gh-pages/v/0.2.5/ng2-material',
                'ng2-bootstrap':'https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/1.0.7/ng2-bootstrap'
            }
      });

      System.import('src/boot.ts')
            .then(null, console.error.bind(console));
    </script>

boot.ts

...

import { Alert } from 'ng2-bootstrap';

//let template = require('./alert-demo.html');  <---------what about this?

@Component({
selector: 'my-app', 
  template: `
 <alert *ngFor="#alert of alerts;#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</butto

   `,
  directives: [childcmp,Alert],

})

export class ParentCmp {

  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
    }
  ];

  constructor(public authService: AuthService){

  }


  closeAlert(i:number) {
    this.alerts.splice(i, 1);
  }

  addAlert() {
    this.alerts.push({msg: 'Another alert!', type: 'warning', closable: true});
  }


}

Solution

  • In fact you need to include the ng2-bootstrap.js into a script element and remove it from your SYstemJS configuration.

    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {
          'src': {defaultExtension: 'ts'},
          'ng2-material': { defaultExtension: 'js' }
        },
        map: {
          'ng2-material': 'https://cdn.rawgit.com/justindujardin/ng2-material/gh-pages/v/0.2.5/ng2-material',
        }
      });
    
      (...)
    <script>
    

    The problem is the way your try to import the Alert component:

    import { Alert } from 'ng2-bootstrap/components/alert';
    

    See this plunkr: http://plnkr.co/edit/YbONWFhPY0IUkXzYo54u?p=preview.