Angular使用表格进行单元格编辑

时间:2018-02-06 22:21:40

标签: angular

使用Angular 5,我有一个具有可编辑列的表。问题是当我点击"编辑图标"在一行中,它启用所有行的输入而不是我选择的行。当我尝试隐藏/显示使用"编辑"旗。如何添加索引逻辑,以便只显示selectedrow的输入字段?

modal.html

<button type="button" class="btn-xs btn-primary (click)="onSave()">Save</button>
<button type="button" class="btn-xs btn-orange" (click)="onCancelEdit()">Cancel</button>

modal.ts

export class ModalComponent {
    @Output() edit: EventEmitter<any> = new EventEmitter();
    @Output() cancelEdit: EventEmitter<any> = new EventEmitter();
    showModal: boolean = true;
    onEdit() {
        // console.log("OK");
        this.edit.emit();
        this.showModal = false;
    }
    onCancelEdit() {
        // console.log("OK");
        this.cancelEdit.emit();
        this.showModal = true;
    }
}

dashboard.html

<tr *ngFor="let bsa of bsaFollowup;let i=index" (click)="GetfollowupID(bsa.ID)">
    <td style="width:8%">{{bsa.ErsaID}}</td>
    <td style="width:18%">{{bsa.AccessFor}}</td>
    <td style="width:11%">
        {{bsa.FollowupDate}}
        <!--<datepicker-popup></datepicker-popup>-->
    </td>
    <td style="width:35%">
        <div *ngIf='edit'>{{bsa.Comments}}</div>
        <div><input type="text" [hidden]='!edit' id="comment" name="ucomment" [(ngModel)]="bsa.Comments" /></div>
    </td>
    <td style="width:15%">{{bsa.BsaName}}</td>
    <td style="width:15%">
        <modal (open)="onOpen($event)" (edit)="onEdit($event)" (cancelEdit)="onCancelEdit($event)"></modal>
    </td>
</tr>

dashboard.ts (日志显示正确的 selectedRowID

onEdit() {
    console.log('on edit: ' + this.selectedRowID);
    this.edit = true;
    console.log('inside edit' + this.edit);
}
onCancelEdit() {
    console.log(this.selectedRowID);
    this.edit = false;
}

1 个答案:

答案 0 :(得分:1)

而不是edit标志,您可以拥有一个editRowIndex,它会定位一个特定的行:

editRowIndex: number = -1;

onEdit(index: number) {
    this.editRowIndex = index;
}
onCancelEdit() {
    this.editRowIndex = -1;
}

行索引将作为@Input值传递给模态组件,并作为edit事件的参数传播:

<modal [rowIndex]="i" (open)="onOpen($event)" (edit)="onEdit($event)" (cancelEdit)="onCancelEdit($event)"></modal>
export class ModalComponent {
    @Input() rowIndex: number = -1;
    @Output() edit: EventEmitter<number> = new EventEmitter();
    @Output() cancelEdit: EventEmitter<any> = new EventEmitter();
    showModal: boolean = true;
    onEdit() {
        this.edit.emit(this.rowIndex);
        this.showModal = false;
    }
    onCancelEdit() {
        this.cancelEdit.emit();
        this.showModal = true;
    }
}

将为已编辑的行显示输入字段:

<input type="text" *ngIf="i === editRowIndex" [(ngModel)]="bsa.Comments" ... />