简体   繁体   中英

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: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
    }
}

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

this.elementRef.nativeElement.innerHTML = this.model

Similarly in onEdit :

var value = this.elementRef.nativeElement.innerHtml

See also

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

Did you try utilizing the innerHTML directive? see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM