Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created September 30, 2021 21:37
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 allenhwkim/637a803cfa4e353ee7f8219fc492a64e to your computer and use it in GitHub Desktop.
Save allenhwkim/637a803cfa4e353ee7f8219fc492a64e to your computer and use it in GitHub Desktop.
Angular text-editable directive
import { Component, ElementRef, HostListener, forwardRef, AfterViewInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: '[text-editable]',
template: '<ng-content></ng-content>',
providers: [ {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TextEditableComponent), multi: true
}],
styles: [`
:host {
padding: 2px 4px;
}
:host[disabled='true'] {
pointer-events: none;
background: #F9F9F9;
}
:host:empty::before {
content: attr(placeholder);
color: #9D9D9D;
}
`]
})
export class TextEditableComponent implements ControlValueAccessor, AfterViewInit {
@HostListener('input') callOnChange() {
this.onChange(this.el.nativeElement.textContent);
}
@HostListener('blur') callOnTouched() { this.onTouched(); }
onChange: (value: string) => void; // init by this.registerOnChange
onTouched: () => void; // init by this.registerOnTouched
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.el.nativeElement.setAttribute('contenteditable', 'true');
}
// called when model is written to view. (model -> view)
writeValue(value) {
this.el.nativeElement.textContent = value || '';
}
registerOnChange(fn) { console.log(fn); this.onChange = fn; }
registerOnTouched(fn) { this.onTouched = fn; }
// called when element property disabled is changed
setDisabledState(val: boolean): void {
this.el.nativeElement.setAttribute('disabled', String(val));
this.el.nativeElement.setAttribute('contenteditable', String(!val));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment