click-edit
Version:
In Angular application, Lets user click on text to edit the contents
101 lines (96 loc) • 3.41 kB
JavaScript
import { __decorate } from 'tslib';
import { EventEmitter, Input, Output, HostListener, Directive, NgModule } from '@angular/core';
let ClickEditDirective = class ClickEditDirective {
constructor(_elementRef, // Reference of the target element.
_renderer2 // Used to update the element without accessing the DOM directly.
) {
this._elementRef = _elementRef;
this._renderer2 = _renderer2;
this.canEdit = true; // Whether the text should be editable or not.
this.multiline = false; // Whether pressing enter should create a newline.
this.contentClass = 'editing'; // Use this to add new classes during editing.
this.onContentChange = new EventEmitter();
}
onClicked() {
if (this.canEdit) {
this.makeEditable();
}
}
onBlurred() {
this.compareContents();
}
onKeyPressed(ev) {
if (ev.keyCode === 13 && !this.multiline) { // Enter key
ev.preventDefault();
this.compareContents();
}
}
makeEditable() {
this._renderer2.addClass(this._elementRef.nativeElement, this.contentClass);
this._renderer2.setAttribute(this._elementRef.nativeElement, 'contentEditable', 'true');
this._elementRef.nativeElement.focus();
this.originalContent = this._elementRef.nativeElement.innerText;
}
compareContents() {
const MODIFIED_CONTENT = this._elementRef.nativeElement.innerText;
if (MODIFIED_CONTENT !== this.originalContent) {
const EDIT = {
contentId: this.contentId,
contentLabel: this.contentLabel,
oldValue: this.originalContent,
newValue: MODIFIED_CONTENT
};
this.onContentChange.emit(EDIT);
}
this.resetEditable();
}
resetEditable() {
this._renderer2.removeClass(this._elementRef.nativeElement, this.contentClass);
this._renderer2.setAttribute(this._elementRef.nativeElement, 'contentEditable', 'false');
}
};
__decorate([
Input()
], ClickEditDirective.prototype, "canEdit", void 0);
__decorate([
Input()
], ClickEditDirective.prototype, "multiline", void 0);
__decorate([
Input()
], ClickEditDirective.prototype, "contentId", void 0);
__decorate([
Input()
], ClickEditDirective.prototype, "contentLabel", void 0);
__decorate([
Input()
], ClickEditDirective.prototype, "contentClass", void 0);
__decorate([
Output()
], ClickEditDirective.prototype, "onContentChange", void 0);
__decorate([
HostListener('click', [('$event')])
], ClickEditDirective.prototype, "onClicked", null);
__decorate([
HostListener('blur')
], ClickEditDirective.prototype, "onBlurred", null);
__decorate([
HostListener('keydown', [('$event')])
], ClickEditDirective.prototype, "onKeyPressed", null);
ClickEditDirective = __decorate([
Directive({
selector: '[clickEdit]'
})
], ClickEditDirective);
let ClickEditModule = class ClickEditModule {
};
ClickEditModule = __decorate([
NgModule({
declarations: [ClickEditDirective],
exports: [ClickEditDirective]
})
], ClickEditModule);
/**
* Generated bundle index. Do not edit.
*/
export { ClickEditDirective, ClickEditModule };
//# sourceMappingURL=click-edit.js.map