我正在尝试在ES5中创建一个自定义指令,每次单击主机元素时都需要执行操作,并且基于验证要么接受单击,要么停止事件的传播。实际上,我正在尝试创建此删除功能:
<button
md-icon-button
confirmClick="Are you sure?"
(click)="delete()">
<md-icon>delete</md-icon>
</button
我坚持如何在ES5中使用ng.core.HostListener
。这是我的自定义指令的代码:
var confirmClick = ng.core.Directive({
selector: '[confirmClick]'
}).Class({
constructor: function() {
console.log('this line is printed out, so things are OK');
}
});
如何在Angular 2 ES5自定义指令中绑定主机元素的click事件?以及如何阻止该事件?
答案 0 :(得分:1)
您可以使用特殊属性host
,如:
var confirmClick = ng.core.Directive({
selector: '[confirmClick]',
host: {
'(click)': 'onClick($event)',
}
}).Class({
constructor: function() {
console.log('this line is printed out, so things are OK');
},
onClick() {
}
});
<强> Plunker Example 强>
另一种方法是将propMetadata
属性设置为构造函数,如:
function ConfirmClass() {}
ConfirmClass.propMetadata = {
onClick: [new ng.core.HostListener('click'), ['$event']]
};
var confirmClick = ng.core.Directive({
selector: '[confirmClick]'
}).Class({
constructor: ConfirmClass,
onClick: function() {
alert(3)
}
});
<强> Plunker Example 强>
另见
答案 1 :(得分:1)
您可以使用:
var directive = ng.core.Directive({
selector: '[directiveAttribute]',
host: {
'(click)': 'doSomething($event)'
}
}).Class({
constructor: function() {
},
doSomething: function(event) {
}
});
要了解更多信息,请阅读官方角度文档中的Spring Cacheable vs CachePut?。