【问题标题】:Angular 2: ContenteditableModel: 2-way data bindingAngular 2:ContenteditableModel:2路数据绑定
【发布时间】:2017-11-05 13:08:00
【问题描述】:

我能够从 contenteditableModel 指令发出一个事件,但我无法接收数据 ' @Input('contenteditableModel') model: any;'我一直不确定。

contenteditableModelChange 工作正常,但不是 contenteditableModel

我更新数据的方式是更新 this.elementRef.nativeElement.textContent,因为我不知道如何使用 [innerHTML]

此指令基于on this guy code: 但为 Angular 2.0 重建。

export class pageContent{
    <p
 contenteditable="true"

(contenteditableModelChange)="runthis($event)"
[contenteditableModel]="text"


></p>

    public text:any = 'ddddd';
    constructor(){}
    runthis(ev){
        this.text  = ev
            console.log('updated done ev', ev)
            console.log('text now should be ', this.text)
    }

}

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

顺便说一句,如果有人建议使用 textContent 属性(而不是 value)和 input 事件来设置我自己的等效属性和事件数据绑定,我已经在这个 plunker 上尝试过它,并且在 IE 上存在光标问题, Firefox 和 Safari 设置为 0

http://plnkr.co/edit/KCeKTPu8dJI0O1nVMPfb?p=preview

【问题讨论】:

  • 你为什么不使用ckeditor呢?
  • 如果我理解正确,如果有人更改 text 它不会在段落中更新?
  • 如果有人更新了innerHTML而不是yes它不会被绑定
  • 你看到我的解决方案了吗

标签: angular data-binding contenteditable


【解决方案1】:

我把ngOnChanges改成了这个:

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

它工作正常。

Plnkr:https://plnkr.co/edit/VW4IJvcv1xjtBKTglWXT?p=preview

根据文档:isFirstChange() 告诉我们是否是第一次分配值。根据您的代码,您只想在第一次更改时更新文本。这是错误的。我认为我们根本不需要担心它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 2016-10-15
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多