Skip to content

Instantly share code, notes, and snippets.

@yokoishioka
Last active August 29, 2023 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokoishioka/f746f261a86c91ffb2a4ffdeef18a096 to your computer and use it in GitHub Desktop.
Save yokoishioka/f746f261a86c91ffb2a4ffdeef18a096 to your computer and use it in GitHub Desktop.
make any element editable with this Angular directive
import { Directive, HostListener, ElementRef, Renderer2, Output, EventEmitter, Input } from '@angular/core';
import { Observable } from 'rxjs';
import { EditUpdate } from '../forms';
@Directive({
selector: '[cesClickEdit]'
})
export class ClickEditDirective {
value: string;
@Input() allowEdit: boolean = true;
@Input() id: number;
@Input() update: string;
@Output() onChange: EventEmitter<EditUpdate> = new EventEmitter();
constructor(
private el: ElementRef,
private renderer: Renderer2
) { }
@HostListener("click", [('$event')]) onClick(event) {
if (this.allowEdit) {
this.makeEditable();
}
}
@HostListener('blur') blurred() {
this.checkValues();
}
@HostListener('keydown', [('$event')]) onKeydown(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.checkValues();
}
}
makeEditable() {
this.renderer.addClass(this.el.nativeElement, "editing");
this.renderer.setAttribute(this.el.nativeElement, "contentEditable", "true");
this.el.nativeElement.focus();
this.setValue(this.el.nativeElement.innerText);
}
checkValues(): Observable<EditUpdate> {
const newValue = this.el.nativeElement.innerText;
if (this.value !== newValue) {
const edit: EditUpdate = {
id: this.id,
update: this.update,
value: newValue
}
this.onChange.emit(edit);
}
this.reset();
return this.onChange;
}
reset() {
this.renderer.removeClass(this.el.nativeElement, "editing");
this.renderer.setAttribute(this.el.nativeElement, "contentEditable", "false");
}
setValue(value: string): string {
this.el.nativeElement.innerText = value;
this.value = value;
return this.value;
}
}
export interface EditUpdate {
id: number,
update: string,
value: string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment