contenteditabledirective.ts 1.49 KB
import { Directive, ElementRef, Input, Output, OnChanges, EventEmitter, HostListener, SimpleChanges
} from '@angular/core';

@Directive({
    selector: '[contenteditableModel]'
})
export class ContenteditableModelDirective implements OnChanges {
    
    @Input('contenteditableModel')
    public model: any;
    
    @Output('contenteditableModelChange')
    public update = new EventEmitter();

    private _lastViewModel: any;

    constructor(private elRef: ElementRef) {}

    public ngOnChanges(changes: SimpleChanges): void {
            if(this._lastViewModel !== changes['model'].currentValue){
                this._lastViewModel = this.model;
                this._refreshView();
            }
    }

    @HostListener('blur')
    public onBlur() {
        if(this.elRef.nativeElement.type == 'checkbox' || this.elRef.nativeElement.type == 'radio'){
            var value = this.elRef.nativeElement.checked;
            this._lastViewModel = value;
            this.update.emit(value);
        }
        else{
            var value = this.elRef.nativeElement.innerText;
            this._lastViewModel = value;
            this.update.emit(value);
        }
    }

    private _refreshView() {
        if(this.elRef.nativeElement.type == 'checkbox' || this.elRef.nativeElement.type == 'radio'){
            this.elRef.nativeElement.value = this.model;
            this.elRef.nativeElement.checked = this.model;
        }
        else{
            this.elRef.nativeElement.innerText = this.model;
        }
    }
}