Getting dependency from Injector manually inside a directive

前端 未结 2 839
鱼传尺愫
鱼传尺愫 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) 
      { }
    
      @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

    提交回复
    热议问题