【问题标题】:angular2 Dynamic add rowangular2动态添加行
【发布时间】:2017-11-20 00:53:59
【问题描述】:

我有要求我可以添加动态行或删除行,这是我的代码

ngOnInit{

this.rows.push({
   id:'',
   name:'',
  age:''
})

addRow(){
let a= {
   id:'',
   name:'',
  age:''
}
this.rows.push(a)
}

deleteRow(index){
this.rows.splice(index,1)
}

}

问题是假设我有三行我在所有三行中都输入了值,如果我删除第二行并添加第三行,第二行和第三行字段将变为空白

<div *ngFor="item in rows;let i =index;">
     <div>
<input type="text" name="name{i}" [(ngModel)]="item.name"> delete/add button here
    </div>
</div>.

【问题讨论】:

  • 为什么要在 ngOnInit 中编写方法?希望是错别字
  • @DmitryGrinko,是的,你是对的,它的错字问题
  • 您的添加/删除 html 代码在哪里?让我们看看出了什么问题。

标签: angular angular2-forms


【解决方案1】:
// TS File Code

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  // Initializtion
  public row: any = [{}];


  // Load on Component Initialization
  public ngOnInit() {

  }


  // Add New Row
  addRow() {
    this.row.push({});
  }

  // Delete Rows
  deleteRow(index: number) {
    this.row.splice(index, 1);
  }

  // Get All Row Values
  getRowValue() {
    console.log(this.row);
  }
}


// HTML File 

<h1>
  Creating Dynamic Textboxes (rows)
</h1>
<input type="button" value="Add Rows" (click)="addRow()"/>
<div *ngFor="let item of row; let i=index">
  <input type="text" name="name{{i}}" [(ngModel)]="item.name"> 
  <input type="button" value="Delete Rows" (click)="deleteRow(index)"/>
</div>

<input type="button" value="Get Rows Value" (click)="getRowValue()"/>

我希望这些代码能帮助您解决您的问题,并希望这些答案能让您满意

谢谢

【讨论】:

【解决方案2】:

您的问题 - ngFor 的第一个索引为零。无论如何,在您的情况下,您不应该使用来自 ngFor 的索引。使用您的项目的 id

delete(id){
   const index = this.rows.map(e => e.id).indexOf(id);
   if(index !== -1) {
       this.rows.splice(index, 1);
   }
}

你的html:

<div *ngFor="let item of rows">
    <span>{{item.name}}</span>
    <span>{{item.age}}</span>
    <button (click)="delete(item.id)"></button>
<div>

希望对你有帮助

【讨论】:

  • 嗨 Dmitry,它没有解决我的问题 deleteRow(index,id) { const index1 = this.rows.findIndex(x => x._id==id); if(index1 !== -1) { this.rows.splice(index1, 1); } };
猜你喜欢
  • 2021-06-12
  • 2017-02-09
  • 2016-08-07
  • 2017-09-26
  • 2017-09-04
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多