簡體   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