Getting dependency from Injector manually inside a directive

前端 未结 2 857
鱼传尺愫
鱼传尺愫 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: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

提交回复
热议问题