1

我試圖在Angular2中使用ngModel實現內聯編輯。我有一個數組需要使用ngFor迭代,也使用ngModel。當我嘗試對該數組應用內嵌編輯時,我只能編輯每個數組變量的一個字符。Angular2使用ngModel和ngFor的內聯編輯

你可以找到一個工作示例here

這裏有一個地方我使用ngModel和ngFor合的部件代碼:

import {Component} from '@angular/core' 
import {InlineEditComponent} from './inline.component'; 
@Component({ 
    selector: 'inline-app', 
    providers: [], 
    template: ` 
    <div> 
     <h2>Inline Editing with Angular 2</h2> 
     <inline-edit [(ngModel)]="editableText" (onSave)="saveEditable($event)"></inline-edit> 
    </div> 
    <div> 
     <ul style="margin:5px;"> 
     <li ngFor #arr [ngForOf]="array" [ngForTrackBy]="customTrackBy"> 
     <inline-edit [(ngModel)]="arr" (onSave)="saveEditable($event)"></inline-edit> 
    </li> 
     // <li style="margin:5px;" *ngFor="let arr of array ; let i=index"> 
     // <inline-edit [(ngModel)]="array[i]" (onSave)="saveEditable($event)"></inline-edit> 
     // </li> 
     </ul> 
    </div> 
    `, 
    directives: [InlineEditComponent] 
}) 
export class InlineApp { 
customTrackBy(index: number, obj: any): any { 
    return index; 
    } 
    editableText = "Click to edit me!"; 
    // Save name to the server here. 
    saveEditable(value){ 
     console.log(value); 
    } 
    array=['bmw','benz','honda']; 
} 

如果有人可以幫助我,這將是巨大的。

回答

2

您正在編輯既是不可變的,又是數組的直接元素的字符串。這意味着只要字符串值發生變化,就會創建一個新的字符串對象,並替換數組中的舊字符串,這又會導致* ngFor爲該字符串重新啓動新組件以替換舊字符串。如果你將console.log('on-constructor')放在InlineEditComponent的構造函數中,每次添加一個字符時都會看到它的調用。

要解決您的問題,請勿直接使用字符串。一類內包裝他們是這樣的:

export class Data { 
    name: string; 
} 

那麼你的數組聲明將是:

array: Data[] = [ 
    {name:"bwm"}, 
    {name:"benz"}, 
    {name:"honda"} 
]; 

這樣,變化只會影響名稱字段,以及包裝對象仍然是相同的;因此ng將不會被觸發重新運行。

修改plnkr:https://plnkr.co/edit/WwGcLlisjGe1cmZOMHhD?p=preview

+0

我原以爲是發生了什麼事情與@ Varun的的問題...你的解決方案是相當不錯的,但取消行動不再取消...它仍然保存了所做的任何更改 –

+0

是的,我沒有對所有其他功能進行理智檢查,應該在那裏發出警告。我的改變純粹是爲了解決他所遇到的問題:) –

+0

實質上,他的解決方案涉及製作一個模型 - 「數據」類。這是實施任何可重複數據對象時推薦的方式。 – BrianRT

0

您可以直接綁定到數組元素,而不是到模板變量:

<li *ngFor="let arr of array; let idx=index; ngForTrackBy:customTrackBy"> 
     <inline-edit [(ngModel)]="array[i]" (onSave)="saveEditable($event)"></inline-edit> 

順便說一句:您的ngFor語法只能在<template>標籤中使用。如果您在其他元素上使用它,則上面使用的語法是必需的。

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngFor

0

這應該在tamplate修改見。

<ul> 
      <li style="margin:5px;" *ngFor="let arr of array ; let i=index; trackBy:customTrackBy"> 
      <inline-edit [(ngModel)]="array[i]" (onSave)="saveEditable($event)"></inline-edit> 
      </li> 
</ul> 

這個功能應該在課堂上說:

export class{ 

customTrackBy(index: number): any { 
    return index; 
    } 
} 

最後的工作代碼:
https://plnkr.co/edit/7SSpZDec2N2zjrSUM04X?p=preview