contenteditabledirective.ts
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;
}
}
}