1

I have a library called foo that contains an angular component called FooContentComponent that renders various types of content:

<ng-container *ngFor="let item of contents">
  <ng-container *ngIf="item.type === 'text'">{{item.text}}</ng-container>
  <ng-container *ngIf="item.type === 'math'">
    <foo-math [formula]="item.formula"></foo-math>
  </ng-continer>
</ng-container>

The FooContentComponent has its own ngModule. Similarly the FooMathComponent also lives in its own ngModule.

Here's the problem: i don't want to explicitly import the FooMathModule in the FooContentModule. Instead i want to leave it up to the application using the foo library to include the FooMathModule if the application wants to render math content. If the application doesn't want to render math content, it will not import the FooMathModule in its app module.

If i don't import the FooMathModule inside FooContentModule i will get an error from the compiler that it doesn't know foo-math. I can get rid of the error by specifying a custom schema in the FooContentModule, but then it still won't render the FooMathComponent.

Can i do this?

1 Answers1

1

You cannot target submodules from the app module's imports / declarations / whatsoever. However what you can do is using a static method like e.g. Angular router has its forRoot()

let imports = [standard imports here];

@NgModule({
  imports
})
export FooContentModule {
  // or call it forRoot if you want
  public static withAdditionalImports(additionalImports: any[]) {
    imports.push.apply(imports, additionalImports);

    return FooContentModule;
  }

}

and then you can use it in any module as

@NgModule({
  imports: [
    FooContentModule.withAdditionalImports(FooMathModule)
  ]
})
export AnyModule {}

Note that if you do it at least once (e.g. in AppModule) it will be available everywhere so it would be enough to just import FooContentModule afterwards

smnbbrv
  • 23,502
  • 9
  • 78
  • 109