Angular 2:array.splice()正在从DOM中删除元素

时间:2017-03-14 07:42:41

标签: javascript angular typescript

我有一个html表,它有默认的检查行。

<table>
    <tr>
        <th></th>
        <th>Id</th>
        <th>Name</th>
        <th>Initial</th>
    </tr>
    <tr *ngFor="let name of names; let i = index">
        <td><input type="checkbox" [checked]="chk" (change)="onTaChange(name, $event.target.checked,i)"></td>
        <td>{{name.id}}</td>
        <td>{{name.Fname}}</td>
        <td>{{name.Initial}}</td>
    </tr>
</table>

我正在形成一个包含未经检查/已检查对象的数组。所以在onTaChange()方法中,我在splice()中传递索引,并希望删除该索引处的对象(表中未经检查的行)。但是如果我取消选中行(对象),即使它们都是不同的对象数组,也会被删除。

我想要的是,让第二个数组只有已检查/未检查的对象行。对此有何帮助?

Plunker

3 个答案:

答案 0 :(得分:1)

原因:数组保留其引用即。当你创建以下内容时:

alteredNames:串[] = this.names;

changedNames不是一个新的数组,而是对原始数组的引用,因此无论你在两个数组中做什么都会反映出来。

解决方案:制作数组的深层副本。使用_.cloneDeep(this.name)

答案 1 :(得分:1)

通过复制数组,有许多现代方法,如:

  • loop
  • Array.from
  • Array.slice
  • Array.concat
  • JSON.parse(JSON.stringify(arr))
  • 来自ES6的
  • [...arr]

但除了loopArray.concat()之外,其中大多数都没有为新数组创建新实例。 因此,在您的情况下,您必须使用Array.forEachArray.pushArray.concat()来复制数组。

这对你来说是plunker。希望它有所帮助。

答案 2 :(得分:0)

您正在使用相同的引用,并且您将整个数组发送到OnTaChange方法

本机slice()方法也用于克隆数组对象

this.alteredNames=this.names.slice(0);

正如Pankaj所说,

this.alteredNames=Object.assign([], this.names)

除了上述内容之外,还可以使用一个非常棒的第三方库来实现相同的结果,

  export class App {
  chk:boolean = true;
  names:string[] = [
    {
      "Fname": "Bunty",
      "id": "1",
      "Initial":"G"
    },
    {
      "Fname": "Ronny",
      "id": "2",
      "Initial":"K"
    },
    {
      "Fname": "Sam",
      "id": "3",
      "Initial":"P"
    },
    {
      "Fname": "James",
      "id": "4",
      "Initial":"M"
    }
    ];
    alteredNames:string[];
  constructor() {
   this.alteredNames=_.clone(this.names) //////////this works
   // or
   this.alteredNames=_.cloneDeep(this.names) // will also work. 
  }

  onTaChange(name:string, $event.target.checked:boolean,i:number){
    if(!checked){
      this.alteredNames.splice(i,1); 
      console.log(this.alteredNames);
    }
    else{
      this.alteredNames.push(name);
    }
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

您应该在此CDN中添加lodash,如下所示

<强> Updated Plunker

另外,

相关问题