1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Standalone component imported in Module requires module to have a service provider

Discussão em 'Angular' iniciado por PaulBunion, Setembro 17, 2025.

  1. PaulBunion

    PaulBunion Guest

    I'm getting a NullInjectorError and I can't figure out why. I've figured out a solution, but I'm not confident it really addresses the root cause.

    In a library, I have a standalone component CurrencyComponent, which imports the CommonModule in order to use the CurrencyPipe:

    @Component({
    selector: 'app-currency'
    standalone: true,
    imports: [CommonModule],
    template: `<div>{{ money | currency }}</div>`
    })
    export class CurrencyComponent {
    money = 10;
    }


    This component's implementation is deeply nested in a bunch of other standalone components also in the same library. These child components are pretty simple and all already import their direct child:

    <!-- For simplicity, I'm just going to list the end result of the templates -->
    <lib-controller>
    <lib-child1>
    <lib-child2>
    <lib-child3>
    <lib-currency />
    </lib-child3>
    </lib-child2>
    </lib-child1>
    </lib-controller>


    The "top level" component is a route's destination in a module:

    import {ControllerComponent} from '@lib/feature/controller';

    const routes = [
    // ...
    {
    path: 'some-route',
    component: ControllerComponent,
    },
    ];
    @NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule],
    })
    export class ProblemRoutingModule {}


    The related module imports the SharedComponent (which contains CommonModule) and the CurrencyComponent (though I realize now this is unnecessary since the component is not directly referenced by any of the module's declared components, but that's irrelevant).

    @NgModule({
    declarations: [/* ... */],
    imports: [
    // ...
    ControllerComponent,
    SharedModule, // exports CommonModule, thus CurrencyPipe???
    ],
    })
    export class ProblemModule {}


    As far as I can see, the CurrencyPipe should be all set, if not redundantly so, because it's imported both by the component using it and the module housing the component's root component! The only way I've found to resolve this is by adding the CurrencyPipe itself to the module's providers array, not even the CommonModule (providers: [CurrencyPipe])!

    My gut tells me this is covering up a problem, not actually fixing it, because as far as I can tell, the module's providers array is, in this setup, entirely unrelated to the CurrencyComponent, which should already have access to the pipe anyways because the component imports CommonModule! Can someone spot the flaw? Because it's certainly eluding me.

    Continue reading...

Compartilhe esta Página