我正在尝试在 Angular 2 中编写一个实用程序指令,它应该与其主机组件协作:
<my-component my-directive></my-component>
特别是,my-directive
将监视某些输入,然后调用 my-component
应该提供的某些函数。例如,我正在编写的指令将封装让组件充当拖放操作的放置区域的样板:
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
});
但是组件本身仍然必须指定当数据被放到它上面时要做什么。这就是我遇到麻烦的地方。如何获取组件对象?或者有更好的办法吗?
哦,我非常感谢 ES6 解决方案(不仅仅是 Typescript)。
最佳答案
您可以使用依赖注入(inject)来获取主机组件的实例。
export const ResourceDropArea = ng.Directive({ /* ... */ }).Class({
constructor(myComponent) {
this.myComponent = myComponent;
},
drop($event) {
this.myComponent.callSomeMethod();
}
});
ResourceDropArea.parameters = [MyComponent];
关于javascript - AngularJS 2 : How to have an 'attribute' directive communicate with its host component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720170/