javascript - AngularJS 2 : How to have an 'attribute' directive communicate with its host component?

标签 javascript angular angular-directive

我正在尝试在 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/

相关文章:

javascript - 使用 html 代码和 javascript 代码作为 flutter web 中的小部件

javascript - 剑道图表上每个项目的多个标签

javascript - 无法使用 "Observable.Of(value)"

javascript - 在 Firefox 中禁用鼠标中键单击和拖动功能

javascript - 如何将对象放入另一个对象 Angular/Javascript

javascript - 2 个不同的阵列到单个阵列组

html - ngModel 的副本也会受到影响

javascript - Angular : filter to replace and complete relative <a href ="/"> paths

javascript - 使用 $attrs 评估其中带有花括号的属性

javascript - 我应该如何在 JavaScript 中一个接一个地执行函数?