ng2-events
Version:
Supercharge your Angular2+ event handling
74 lines (73 loc) • 3.33 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConditionEventDirective = void 0;
var core_1 = require("@angular/core");
var i0 = require("@angular/core");
/**
* Conditionally apply event listeners to an element
*
* Usage:
* <button [ev-condition]="isActive()"
* ev-events="click"
* (ev-fire)="handleClick($event)">...</button>
*
* Notes:
* The [ev-events] property can be either a string or an array of strings to handle multiple events
*/
var ConditionEventDirective = /** @class */ (function () {
function ConditionEventDirective(elm, renderer) {
this.elm = elm;
this.renderer = renderer;
this.fire = new core_1.EventEmitter();
this.listeners = [];
}
ConditionEventDirective.prototype.ngOnChanges = function (changes) {
var _this = this;
this.unregisterAll();
if (!this.condition || !this.events)
return;
var events = (typeof (this.events) === 'string')
? [this.events]
: this.events;
this.listeners = events.map(function (x) { return _this.addListener(x); });
};
ConditionEventDirective.prototype.ngOnDestroy = function () {
this.unregisterAll();
};
ConditionEventDirective.prototype.unregisterAll = function () {
this.listeners.forEach(function (x) { return x(); });
this.listeners = [];
};
ConditionEventDirective.prototype.addListener = function (eventName) {
var _this = this;
var colon = eventName.indexOf(':');
var handler = function ($event) { return _this.fire.next($event); };
if (colon === -1) {
return this.renderer.listen(this.elm.nativeElement, eventName, handler);
}
else {
var scope = eventName.slice(0, colon);
var realEventName = eventName.slice(colon + 1);
return this.renderer.listen(scope, realEventName, handler);
}
};
ConditionEventDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.2", ngImport: i0, type: ConditionEventDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }], target: i0.ɵɵFactoryTarget.Directive });
ConditionEventDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.0.2", type: ConditionEventDirective, selector: "[ev-condition]", inputs: { condition: ["ev-condition", "condition"], events: ["ev-events", "events"] }, outputs: { fire: "ev-fire" }, usesOnChanges: true, ngImport: i0 });
return ConditionEventDirective;
}());
exports.ConditionEventDirective = ConditionEventDirective;
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.2", ngImport: i0, type: ConditionEventDirective, decorators: [{
type: core_1.Directive,
args: [{
selector: '[ev-condition]'
}]
}], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.Renderer2 }]; }, propDecorators: { condition: [{
type: core_1.Input,
args: ['ev-condition']
}], events: [{
type: core_1.Input,
args: ['ev-events']
}], fire: [{
type: core_1.Output,
args: ['ev-fire']
}] } });