Reputation: 753
I'm trying to create a custom directive in ES5, that needs to take action each time the host element is clicked, and based on a validation either accepts the click, or stops the event's propagation. In fact, I'm trying to create this delete functionality:
<button
md-icon-button
confirmClick="Are you sure?"
(click)="delete()">
<md-icon>delete</md-icon>
</button
I'm stuck at how to use ng.core.HostListener
in ES5. Here's my custom directive's code:
var confirmClick = ng.core.Directive({
selector: '[confirmClick]'
}).Class({
constructor: function() {
console.log('this line is printed out, so things are OK');
}
});
How should I bind to the host element's click event in Angular 2 ES5 custom directive? and how to stop that event?
Upvotes: 2
Views: 136
Reputation: 214175
There is special property host
that you can use like:
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() {
}
});
Another way is setting propMetadata
property to constructor function like:
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)
}
});
See also
Upvotes: 1
Reputation: 35842
You can use:
var directive = ng.core.Directive({
selector: '[directiveAttribute]',
host: {
'(click)': 'doSomething($event)'
}
}).Class({
constructor: function() {
},
doSomething: function(event) {
}
});
To understand it more, read TypeScript to JavaScript from official angular documents.
Upvotes: 1