How to add providers to Injector dynamically?

后端 未结 4 1126
北海茫月
北海茫月 2021-01-01 20:42

Each component can specify new Providers using its providers property in ComponentMetadata.

Is there a way to specify provider

4条回答
  •  忘掉有多难
    2021-01-01 21:40

    There is one way to create component using ViewContainerRef, where is allowed to pass injector so I guess this should be possible but it is limited to create components dynamically:

    Create Injector:

    static create(options: {providers: StaticProvider[], parent?: Injector, name?: string}): Injector;
    
    // @param injector The injector to use as the parent for the new component.
    
    abstract createComponent(
        componentFactory: ComponentFactory, index?: number, injector?: Injector,
        projectableNodes?: any[][], ngModule?: NgModuleRef): ComponentRef;
    

    Pseudo code:

    class FooComponent {
    
      constructor(
        private readonly injector: Injector,
        private readonly viewContainer: ViewContainerRef){
        const customInjector = this.injector.create({ providers: [FooService], parent: injector });
        this.viewContainer.createComponent(componentFactory, 0, customInjector );
        ...
      }
    }
    

    Or similarly use Portal from Angular CDK.

提交回复
热议问题