I am currently working on developing a versatile directive that can take a class type for validating rules. Depending on the rule specified in the class, the directive will either display or hide an element.
This is my progress so far.
Check out the PLUNKER demo here
Custom-Directive.js
@Directive({
selector: '[customDirective]'
})
export class CustomDirective {
constructor(private _viewContainer: ViewContainerRef,
private _template: TemplateRef<Object>)
{ }
@Input() set customDirective(rule: string) {
// The rule class type will be provided as a string
// How do I utilize the string token to fetch dependencies from the injector?
// Currently hardcoding it
// Will the injector create a new instance or pass on an existing one from 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 *customDirective="'AdminOnly'">
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
However, I am facing two challenges:
- I keep encountering the error
No Provider for AuthService
- I'm unsure about how to retrieve dependencies from the Injector using the class name as a string rather than its type
I would greatly appreciate any suggestions or feedback on whether my approach is correct or if there are errors in my implementation.