Angular2:Contenteditable div没有按预期工作

时间:2017-03-20 14:37:14

标签: javascript html angular contenteditable

当服务器存储的html文本绑定到contenteditable div时。 html不会被处理和渲染,而是按原样呈现。

例如,来自服务器的html文本下面呈现为文本而不是html。

<br>---------- Forwarded message ----------<br>From: Someone &lt;<a href="mailto:sh@gmail.com" target="_blank">sh@gmail.com</a>&gt;

以下是当前代码:

HTML代码:

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

2 个答案:

答案 0 :(得分:2)

如果您想获取html,请在innerHTML

中使用textContent代替refreshView
this.elementRef.nativeElement.innerHTML = this.model

同样在onEdit

var value = this.elementRef.nativeElement.innerHtml

另见

答案 1 :(得分:0)

请避免直接操纵DOM,因为它违背了角度2的思维模式。

您是否尝试使用innerHTML指令? see