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