Getting dependency from Injector manually inside a directive

前端 未结 2 838
鱼传尺愫
鱼传尺愫 2020-12-20 04:03

I am trying to create a generic directive which will take a class type for rule validation and according to the rule in the class the directive will either show or hide an e

相关标签:
2条回答
  • 2020-12-20 04:19

    You need to pass the parent injector like

    export class MyIfDirective {
      constructor(private injector:Injector, private _viewContainer: ViewContainerRef,
        private _template: TemplateRef<Object>) 
      { }
    
      @Input() set myIf(rule: string) {
        let resolvedProviders = ReflectiveInjector.resolve([AdminOnly]);
        let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
    
        let adminOnly : IRule = childInjector.get(AdminOnly);
        let show = adminOnly.shouldShowElement();
        show ? this.showItem() : this.hideItem();
      }
      private showItem() {
        this._viewContainer.createEmbeddedView(this._template);
      }
    
      private hideItem() {
        this._viewContainer.clear();
      }
    }
    

    See also Inject service with ReflectiveInjector without specifying all classes in the dependency tree

    0 讨论(0)
  • 2020-12-20 04:24

    Just update for Angular version 10+:

    • From your service:
      @Injectable({
        providedIn: 'any'
      })
      export class AdminOnly { ... }
    
    • In your directive or a pure function, ...:
     import { Injector } from '@angular/core';
    
     ...
     const injector: Injector = Injector.create({
       providers: [{provide: AdminOnly, deps: []}]
     });
     const adminOnly: AdminOnly = injector.get(AdminOnly);
    
     let show = adminOnly.shouldShowElement();
     ...
    

    See more

    0 讨论(0)
提交回复
热议问题