Shyamal Parikh
Shyamal Parikh

Reputation: 3068

Angular2: Contenteditable div doesn't work as expected

When server stored html text is bound to contenteditable div. The html is not processed and rendered, instead it is rendered as it is.

For example,below html text from server is rendered as text instead of in html.

<br>---------- Forwarded message ----------<br>From: Someone &lt;<a href="mailto:[email protected]" target="_blank">[email protected]</a>&gt;

Here is the current code:

HTML Code:

 <div class="description-input" 
             placeholder="Enter Description"
             ion-content
             contenteditable="true"
             [(contenteditableModel)]="description">
        </div>

Javascript:

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

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

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

    constructor(
        private elementRef: ElementRef
    ) {
        //console.log('ContentEditableDirective.constructor');
    }

    ngOnChanges(changes) {
        //console.log('ContentEditableDirective.ngOnChanges');
        //console.log(changes);
        if (changes.model.isFirstChange())
            this.refreshView();
    }

    onEdit() {
        //console.log('ContentEditableDirective.onEdit');
        var value = this.elementRef.nativeElement.innerText
        this.update.emit(value)
    }

    private refreshView() {
        //console.log('ContentEditableDirective.refreshView');
        this.elementRef.nativeElement.textContent = this.model
    }
}

Upvotes: 0

Views: 526

Answers (2)

yurzui
yurzui

Reputation: 214017

If you want to get html then use innerHTML instead of textContentin refreshView

this.elementRef.nativeElement.innerHTML = this.model

Similarly in onEdit:

var value = this.elementRef.nativeElement.innerHtml

See also

Upvotes: 2

Angular Dev
Angular Dev

Reputation: 4916

Please avoid direct manipulation of the DOM as it goes against the angular 2 mindset.

Did you try utilizing the innerHTML directive? see

Upvotes: 0

Related Questions