使用Angular5从表中删除一行的方法如下:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
rows: this.formBuilder.array([])
});
}
get rows(): FormArray {
return this.form.get('rows') as FormArray;
}
addRow() {
this.rows.push(this.formBuilder.group({
// 定义表单中的字段
}));
}
deleteRow(index: number) {
this.rows.removeAt(index);
}
}
*ngFor
指令循环显示表格的每一行,并为每一行添加删除按钮:<form [formGroup]="form">
<table>
<tr *ngFor="let row of rows.controls; let i = index" [formGroupName]="i">
<!-- 显示表单字段 -->
<td>{{ row.controls.field1.value }}</td>
<td>{{ row.controls.field2.value }}</td>
<!-- 添加删除按钮 -->
<td><button type="button" (click)="deleteRow(i)">删除</button></td>
</tr>
</table>
</form>
<button type="button" (click)="addRow()">添加行</button>
现在,当你点击"添加行"按钮时,会在表格中添加一行,并且每一行都有一个"删除"按钮。当你点击"删除"按钮时,对应的行会被从表格中删除。
请注意,以上代码只是一个示例,你需要根据你的实际需求进行适当的修改。此外,你可能还需要在你的应用中引入其他必要的模块和服务,例如ReactiveFormsModule
等。
领取专属 10元无门槛券
手把手带您无忧上云