Angular 2 - Edit table rows inline, then save the new data

前端 未结 2 578
一整个雨季
一整个雨季 2021-02-01 11:14

I am trying to make a component that shows data in rows from TableData model,

export class TableData{
    constructor(
        public id: number,
        public          


        
2条回答
  •  鱼传尺愫
    2021-02-01 11:37

    I was looking an answer to the same question. First, I got here. Later, I found amazing article with answer you was looking for.

    Updated: I have udpated plunk as well as directive code to latest verstion of angular

    Directive: contenteditableModel

    
    

    https://www.namekdev.net/2016/01/two-way-binding-to-contenteditable-element-in-angular-2/

    https://plnkr.co/edit/SRLYoX5chNYJIpZ4iqsG?p=preview

    import {
        Directive,
        ElementRef,
        Input,
        Output,
        OnChanges,
        EventEmitter,
        HostListener,
        SimpleChanges
    } from '@angular/core';
    
    /**
     * 
     */
    @Directive({
        selector: '[contenteditableModel]'
    })
    export class ContenteditableModelDirective implements OnChanges {
    
        @Input('contenteditableModel')
        public model: any;
    
        @Output('contenteditableModelChange')
        public update = new EventEmitter();
    
        private _lastViewModel: any;
    
        constructor(private elRef: ElementRef) {}
    
        public ngOnChanges(changes: SimpleChanges): void {
            if(this._lastViewModel !== changes['model'].currentValue){
                this._lastViewModel = this.model;
                this._refreshView();
            }
        }
    
        @HostListener('blur')
        public onBlur() {
            var value = this.elRef.nativeElement.innerText;
            this._lastViewModel = value;
            this.update.emit(value);
        }
    
        private _refreshView() {
            this.elRef.nativeElement.innerText = this.model;
        }
    }
    

提交回复
热议问题