exclude components from ng-bootstrap module in ang

2019-09-14 21:21发布

问题:

I want to import some specific components from ng-bootstrap module in angular 2. can I do that?

I have custom tabset created from existing ng-bootstrap component. After importing ng-bootstrap I have getting module duplication error.

How can i handle this.!!

回答1:

It is easy: just import individual modules from ng-bootstrap instead of importing the whole NgbModule. For example to only import alert-related functionality you would do:

import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap/alert/alert.module';

...

@NgModule({
  imports: [BrowserModule, NgbAlertModule.forRoot()], 
  declarations: [App]
  bootstrap: [App]
}) 
export class AppModule {}

Of course you would have to import and list all the modules that you are using but the advantage here is that you can precisely reference only things that are used in your application.



回答2:

Two common mistakes done by people who are using ng-bootstrap for the first time:

  1. Include both NgbModule and individual components and get that duplication error.
  2. Miss "Module" suffix while importing most of components
    (e.g. import { NgbTabset } from ... instead of import { NgbTabsetModule } from ...)

So as the answer to your question just remove the NgbModule if you've imported that and import NgbTabsetModule instead.

Just like this:

// Remove this line -> import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgbTabsetModule } from '@ng-bootstrap/ng-bootstrap';
//...
@NgModule({
  imports: [
    // ...
    NgbTabsetModule,
  ],
  declarations: [YourComponent]
})
export class YourComponent {}

P.S. Also there is no need to provide full path while importing the component as is mentioned in other answer(s). Importing from '@ng-bootstrap/ng-bootstrap' works fine.