繁体   English   中英

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

[英]Angular 2: array.splice() is removing the elements from DOM

我有一个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()中传递了索引,并希望删除该索引处的对象(表中未选中的行)。 但是,如果我取消选中行(对象),即使它们都是不同的对象数组,它们也会被删除。

我想要的是,有一个第二个数组,其中只有对象的选中/未选中的行。 有什么帮助吗?

柱塞

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

alteredNames:string [] = this.names;

alteredNames不是新的Array,而是对原始数组的引用,因此,您在这两个数组中所做的任何操作都会在两个数组中均得到反映。

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

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

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

但是除了loopArray.concat()之外,大多数都没有为新数组创建新实例。 因此,在您的情况下,您必须使用循环方法,即使用Array.forEachArray.push或通过Array.concat()复制数组。

这对你来说是个矮人 希望能帮助到你。

您使用相同的引用,并将整个数组发送到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,如下所示

更新的柱塞

也,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM