Why Angular provider is not detectedin standalone component?

Discussão em 'Angular' iniciado por ruddnisrus, Setembro 10, 2024.

  1. ruddnisrus

    ruddnisrus Guest

    I have specific problem.

    I have component, which I will build by my custom builder. This builder build my component in ESM format.

    My component code (which will be builded) is simple standalone component which imports MyModule.

    MyModule.ts

    import { NgModule } from "@angular/core";
    import { MyTestLibModule } from "my-test-lib"
    @NgModule({
    exports: [
    MyTestLibModule,
    ],
    imports: [
    MyTestLibModule,
    ]
    })
    export default class MyModule {
    }


    In my test lib I have simple structure like following:

    I have my-test-lib.component.ts which creates MyContentComponent on demand <on click>.

    @Component({
    selector: 'lib-my-test-lib',
    templateUrl: './my-test-lib.component.html',
    styles: ``
    })
    export class MyTestLibComponent {
    private popRef: OverlayRef;

    constructor(private overlay: Overlay, private viewContainerRef: ViewContainerRef) {
    this.popRef = this.overlay.create();
    }

    createDynamicComponent(): void {
    const portal = new ComponentPortal(MyContentComponent, this.viewContainerRef);
    let componentRef: ComponentRef<MyContentComponent> = this.popRef.attach(portal);
    }
    }


    MyContentComponent is empty , it has child component MyChildComponent in html

    <app-my-child></app-my-child>


    and MyChildComponent

    @Component({
    selector: 'app-my-child',
    templateUrl: './my-child.component.html',
    styleUrls: ['./my-child.component.css']
    })
    export class MyChildCOMponent{

    constructor(private _init: MyTestLibService) {
    console.log(this._init.someValue, 'This is value from component')
    }
    }


    The MyTestLibService is very simple component BUT NOT ROOT

    @Injectable()
    export class MyTestLibService {
    constructor() { }

    someValue: string = 'This is value from MyTestLibService'
    }


    In MylibModule of course I add it to providers array.

    And here I get error. When I compile it by my custom builder there is error

    NullInjectorError: No provider for MyTestLibService!


    I have to add this service to providers for MyContentComponent to make it works...

    Additionaly, when I just put selector with MyContentComponent in main lib HTML it works without any issue...

    Any idea why it doesn't recognize provider when I build it to ESM ?

    Continue reading...

Compartilhe esta Página