javascript - Getting dependency from Injector manually inside a directive -


i trying create generic directive take class type rule validation , according rule in class directive either show or hide element.

this attempt far.

plunker demo

myif-directive.ts

@directive({   selector: '[myif]' }) export class myifdirective {   constructor(private _viewcontainer: viewcontainerref,     private _template: templateref<object>)    { }    @input() set myif(rule: string) {     //rule class type come string     //how can use string token dependency injector?     //currently harcoded     //will injector create new instance or pass on instance parent?     let injector = reflectiveinjector.resolveandcreate([adminonly]);     let adminonly : irule = injector.get(adminonly);     let show = adminonly.shouldshowelement();     show ? this.showitem() : this.hideitem();   }   private showitem() {     this._viewcontainer.createembeddedview(this._template);   }    private hideitem() {     this._viewcontainer.clear();   } } 


app-component.ts

@component({   selector: 'my-app',   template: `     <div *myif="'adminonly'">       <h2>hello {{name}}</h2>     </div>   `, }) export class app {   name:string;   constructor() {     this.name = 'angular2'   } } 

but stuck in 2 places:

  1. i keep getting error no provider authservice
  2. i not know how can dependency injector using class name string rather type

any suggestion whether right way or going wrong highly appreciated.

you need pass 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 inject service reflectiveinjector without specifying classes in dependency tree


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -