Angular 2 contenteditable

后端 未结 7 1443
野的像风
野的像风 2020-12-15 05:07

In Angular 2 how can I make two way data binding with a contenteditable div?

Text Field

7条回答
  •  伪装坚强ぢ
    2020-12-15 05:37

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

提交回复
热议问题