Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Angular 2 contenteditable


In Angular 2 how can I make two way data binding with a contenteditable div?

<div class="editable" contenteditable="true">
    <h1>Text Field</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra felis in sem porta feugiat.</p>
like image 363
Codrut Tapu Avatar asked Aug 18 '16 23:08

Codrut Tapu

People also ask

Is Contenteditable angular?

Angular does not have an accessor for contenteditable , so if you want to use it with forms you will have to write one.

What does Contenteditable mean?

The contenteditable attribute specifies whether the content of an element is editable or not. Note: When the contenteditable attribute is not set on an element, the element will inherit it from its parent.

Can I use NgModel on div?

NgModel expects the bound element to have a value property, which div s don't have. That's why you get the No value accessor error.

What is the use of Contenteditable?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

1 Answers

I've adapted Isetty's answer to work with the release version of Angular 2.0, now it is available. Apart from working with the release version, I've also added a keyup event and used textContent rather than innerText, because that suites my application better. You may wish to change these things.

import {Directive, ElementRef, Input, Output, EventEmitter, OnChanges} from "@angular/core";

    selector: '[contenteditableModel]',
    host: {
        '(blur)': 'onEdit()',
        '(keyup)': 'onEdit()'

export class ContentEditableDirective implements OnChanges {
    @Input('contenteditableModel') model: any;
    @Output('contenteditableModelChange') update = new EventEmitter();

        private elementRef: ElementRef
    ) {

    ngOnChanges(changes) {
        if (changes.model.isFirstChange())

    onEdit() {
        var value = this.elementRef.nativeElement.innerText

    private refreshView() {
        this.elementRef.nativeElement.textContent = this.model
like image 135
David Avatar answered Sep 25 '22 13:09