1. 在根模塊下導入
import { ReactiveFormsModule } from '@angular/forms';
2.ts 文件
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder ,FormArray } from '@angular/forms';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent {
constructor(private router: Router, private formBuilder: FormBuilder) { }
public fg:FormGroup =this.formBuilder.group(
{
// 創建數組對象
arrayList:this.formBuilder.array([])
}
);
/**
* 獲取數組對象
*/
get arrayList()
{
return this.fg.get('arrayList') as FormArray;
}
/**
* 創建一行組件
*/
createRow(){
return this.formBuilder.group({
firstName:[''],
age:[''],
profession:[''],
});
}
/**
* 增加一行事件
*/
addBtn(){
this.arrayList.push(this.createRow());
}
/**
* 刪除一行事件
*/
delBtn(i:number){
this.arrayList.removeAt(i);
}
}
3.HTML
<form [formGroup]="fg">
<table class="table table-bordered">
<tr><td>姓名</td><td>年齡</td><td>職業</td><td></td></tr>
<ng-container formArrayName='arrayList'>
<ng-container *ngFor="let row of arrayList.controls;let i =index">
<tr>
<ng-container [formGroup]="row">
<td>
<input type="text" class='form-control' formControlName="firstName">
</td>
<td>
<input type="text"class='form-control' formControlName="age">
</td>
<td>
<input type="text" class='form-control' formControlName="profession">
</td>
<td>
<button class='form-control' (click)="delBtn(i)">刪除</button>
</td>
</ng-container>
</tr>
</ng-container>
</ng-container>
</table>
</form>
<button (click)="addBtn()">添加</button>
4.引入bootstrap
