Created
January 23, 2016 01:29
-
-
Save Namek/8387d6cc4f4d6857e277 to your computer and use it in GitHub Desktop.
Angular 2 directive: two-way binding to contenteditable
This file contains hidden or 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
@Component({ | |
selector: 'test-component' | |
}) | |
@View({ | |
directives: [ContenteditableModel] | |
template: ` | |
<h1 contenteditable="true" [(contenteditableModel)]="someObj.someProperty"></h1> | |
{{someObj | json}} | |
` | |
}) | |
export class TestCmp { | |
someObj = {someProperty: "startValue"} | |
} |
This file contains hidden or 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, 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