Angular 2 contenteditable [英] Angular 2 contenteditable
本文介绍了Angular 2 contenteditable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< div class =editable在Angular 2中,我怎样才能让双向数据绑定到可以理解的div? contenteditable =true>
< h1>文字栏位< / h1>
< p> Lorem ipsum dolor坐在amet,consectetur adipiscing elit。在sem porta feugiat的pharetra felis中。< / p>
< / div>
解决方案
我调整了Isetty的解决方案Angular 2.0的版本,现在可用。除了使用发布版本之外,我还添加了一个关键事件,并使用textContent而不是innerText,因为它更好地套用了我的应用程序。
import {Directive,ElementRef,Input,Output,EventEmitter,OnChanges} from@angular /核心;
$ b @Directive({
selector:'[contenteditableModel]',
host:{
'(blur)':'onEdit()',
'(keyup)':'onEdit()'
}
})
导出类ContentEditableDirective实现OnChanges {
@Input('contenteditableModel')模型:任何;
@Output('contenteditableModelChange')update = new EventEmitter();
构造函数(
private elementRef:ElementRef
){
console.log('ContentEditableDirective.constructor');
}
ngOnChanges(变更){
console.log('ContentEditableDirective.ngOnChanges');
console.log(更改);
if(changes.model.isFirstChange())
this.refreshView();
onEdit(){
console.log('ContentEditableDirective.onEdit');
var value = this.elementRef.nativeElement.innerText
this.update.emit(value)
}
private refreshView(){
console。日志( 'ContentEditableDirective.refreshView');
this.elementRef.nativeElement.textContent = this.model
}
}
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>
</div>
解决方案
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";
@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
}
}
这篇关于Angular 2 contenteditable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文