import { Component } from ‘@angular/core‘;
import { FormGroup, FormBuilder ,FormArray } from ‘@angular/forms‘;
@Component({
selector: ‘app-news‘,
templateUrl: ‘./news.component.html‘,
styleUrls: [‘./news.component.css‘]
})
export class NewsComponent {
constructor(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);
}
/**
* 添加数据
*/
addData(){
this.arrayList.controls.forEach((item,index)=>{
item.patchValue({
firstName:‘zhangsan‘+index,
age:20+index,
profession:‘java‘,
})
});
}
/**
* 打印数据
*/
printData(){
console.log(this.fg.get(‘arrayList‘).value);
}
/**
* 清空数据
*/
clearData(){
this.arrayList.controls.forEach(item=>{
item.patchValue({
firstName:‘‘,
age:‘‘,
profession:‘‘,
})
})
}
}