0

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:sh@gmail.com" target="_blank">sh@gmail.com</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
    }
}
Shyamal Parikh
  • 2,988
  • 4
  • 37
  • 78
  • Possible duplicate of [angular 2 html binding](http://stackoverflow.com/questions/31548311/angular-2-html-binding) – realappie Mar 20 '17 at 14:53

2 Answers2

2

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

Shyamal Parikh
  • 2,988
  • 4
  • 37
  • 78
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • While this works great, you are accessing the DOM directly which is not good :/ – realappie Mar 20 '17 at 14:52
  • @Abdel If you're not going to use server-side rendering and utilizing Angulars WebWorkers then i don't see this problem https://angular.io/docs/ts/latest/guide/ngmodule.html#!#declare-directives-and-components – yurzui Mar 20 '17 at 15:08
  • This works great, but `onEdit` again converts the html to text. – Shyamal Parikh Mar 20 '17 at 15:34
  • 1
    Replace `innerText` with `innetHTML` within `onEdit` method – yurzui Mar 20 '17 at 15:36
0

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

Did you try utilizing the innerHTML directive? see

Community
  • 1
  • 1
realappie
  • 4,656
  • 2
  • 29
  • 38