I'm trying to write a utility directive in Angular 2, which should collaborate with its host component:
<my-component my-directive></my-component>
In particular, my-directive
will watch for certain inputs, then calls certain functions that should be provided by my-component
. For example, the directive I'm writing would encapsulate the boilerplate for having a component act as a drop-area for a drag-and-drop operation:
export const ResourceDropArea = ng.Directive({
selector: '[resource-drop-area]',
inputs: ['data: resourceDropArea'],
host: {
'(dragenter)': ' dragenter($event) ',
'(dragleave)': ' dragleave($event) ',
'(dragover)': ' dragover ($event) ',
'(drop)': ' drop ($event) '
}
}).Class({
constructor() {}
// event handling code
});
But the component itself would still have to specify what to do when data is dropped on it. That's where I'm having trouble. How do I get a hold of the component object? Or is there a better way?
Oh, and I would much appreciate an ES6 solution (not just Typescript).
You can use dependency injection to get the instance of the host component.
export const ResourceDropArea = ng.Directive({ /* ... */ }).Class({
constructor(myComponent) {
this.myComponent = myComponent;
},
drop($event) {
this.myComponent.callSomeMethod();
}
});
ResourceDropArea.parameters = [MyComponent];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.