Skip to content

Instantly share code, notes, and snippets.

@Namek
Created January 23, 2016 01:29
Show Gist options
  • Save Namek/8387d6cc4f4d6857e277 to your computer and use it in GitHub Desktop.
Save Namek/8387d6cc4f4d6857e277 to your computer and use it in GitHub Desktop.
Angular 2 directive: two-way binding to contenteditable
@Component({
selector: 'test-component'
})
@View({
directives: [ContenteditableModel]
template: `
<h1 contenteditable="true" [(contenteditableModel)]="someObj.someProperty"></h1>
{{someObj | json}}
`
})
export class TestCmp {
someObj = {someProperty: "startValue"}
}
import {Directive, ElementRef, Input, Output} from "angular2/core";
import {EventEmitter} from "angular2/src/facade/async";
import {OnChanges} from "angular2/core";
import {isPropertyUpdated} from "angular2/src/common/forms/directives/shared";
@Directive({
selector: '[contenteditableModel]',
host: {
'(blur)': 'onBlur()'
}
})
export class ContenteditableModel implements OnChanges {
@Input('contenteditableModel') model: any;
@Output('contenteditableModelChange') update = new EventEmitter();
private lastViewModel: any;
constructor(private elRef: ElementRef) {
}
ngOnChanges(changes) {
if (isPropertyUpdated(changes, this.lastViewModel)) {
this.lastViewModel = this.model
this.refreshView()
}
}
onBlur() {
var value = this.elRef.nativeElement.innerText
this.lastViewModel = value
this.update.emit(value)
}
private refreshView() {
this.elRef.nativeElement.innerText = this.model
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment