Angular 2 contenteditable

后端 未结 7 1439
野的像风
野的像风 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:46

    Please refer this code. It will work you i think.

    app.ts

    @Component({
        selector: 'test-component'
    })
    @View({
        directives: [ContenteditableModel]
        template: `
            

    {{someObj | json}} ` }) export class TestCmp { someObj = {someProperty: "startValue"} }

    contenteditableModel.ts:

    import {Directive, ElementRef, Input, Output} from "angular2/core";
    import {EventEmitter} from "angular2/src/facade/async";
    import {OnChanges} from "angular2/core";
    import {isPropertyUpdated} from "angular2/src/common/forms/directives/shared";
    
    @Directive({
        selector: '[contenteditableModel]',
        host: {
            '(blur)': 'onBlur()'
        }
    })
    export class ContenteditableModel implements OnChanges {
        @Input('contenteditableModel') model: any;
        @Output('contenteditableModelChange') update = new EventEmitter();
    
        private lastViewModel: any;
    
    
        constructor(private elRef: ElementRef) {
        }
    
        ngOnChanges(changes) {
            if (isPropertyUpdated(changes, this.lastViewModel)) {
                this.lastViewModel = this.model
                this.refreshView()
            }
        }
    
        onBlur() {
            var value = this.elRef.nativeElement.innerText
            this.lastViewModel = value
            this.update.emit(value)
        }
    
        private refreshView() {
            this.elRef.nativeElement.innerText = this.model
        }
    }
    

    For the extra inputs i found a link for you. https://www.namekdev.net/2016/01/two-way-binding-to-contenteditable-element-in-angular-2/

提交回复
热议问题