Last active
August 29, 2023 23:36
-
-
Save yokoishioka/f746f261a86c91ffb2a4ffdeef18a096 to your computer and use it in GitHub Desktop.
make any element editable with this Angular directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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