我有要求我可以添加动态行或删除行,这是我的代码
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>.
答案 0 :(得分: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()"/>
我希望这些代码可以帮助您解决问题,并希望这些答案会令人满意
谢谢
答案 1 :(得分:0)
您的问题 - 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>
希望有所帮助