加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:ContenteditableModel:双向数据绑定

发布时间:2020-12-17 07:02:07 所属栏目:安全 来源:网络整理
导读:我能够从contenteditableModel指令发出一个事件,但我无法接收数据’@Input(‘contenteditableModel’)模型:any;’我一直都没有定义. contenteditableModelChange工作正常,但不是contenteditableModel 我更新数据的方法是更新this.elementRef.nativeElement.
我能够从contenteditableModel指令发出一个事件,但我无法接收数据’@Input(‘contenteditableModel’)模型:any;’我一直都没有定义.

contenteditableModelChange工作正常,但不是contenteditableModel

我更新数据的方法是更新this.elementRef.nativeElement.textContent,因为我无法弄清楚如何使用[innerHTML]

该指令基于on this guy code:
但重建角度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属性(而不是值)和输入事件设置我自己的等效属性和事件数据绑定,我已经在这个plunker上尝试了它,并且在IE,Firefox和Safari上存在游标问题设置为0

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

解决方法

我将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()告诉我们是否第一次分配值.根据您的代码,您只想在第一次更改时更新文本.哪个错了.我认为我们根本不需要担心它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读