초기 결과
행 추가를 클릭합니다
데이터 추가를 클릭합니다
인쇄 데이터를 클릭
클리어 데이터를 클릭
TS는 코드의 일부를 설명
/ **
* 오브젝트의 배열을 얻기
* /
) (ArrayList를 얻을
{
this.fg.get ( 'ArrayList를')를 호출
FormArray 등을;
}
컨트롤의 ArrayList는 검색된 HTML 페이지를 객체
/ **
* 데이터 추가
* /
는, addData () {
this.arrayList
.
제어
.forEach ((항목, 인덱스) => {
// 여기에
this.arrayList
에서
FormArray은을 얻기 위해 GET ArrayList를 () 메소드를 객체
ArrayList에이 속성을 제어에 의해 통제 구성 요소를 얻으려면 FormArray
angular2 소스 스크린 샷
![](https://img2018.cnblogs.com/i-beta/1670967/202001/1670967-20200111173041122-386122645.png)
item.patchValue ({
firstName을 'zhangsan'+ 인덱스,
연령 : 20 + 인덱스,
직업 : '자바'
})
});
}
링크 angular2의 공식 문서에 patchValue 참조의 설명
1. 오기 모듈
import { ReactiveFormsModule } from '@angular/forms'; 红线标记为需要引入代码
![](https://img2018.cnblogs.com/i-beta/1670967/202001/1670967-20200111171720411-1503200694.png)
2.HTML 部分
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>
<button (click)="addData()">添加数据</button>
<button (click)="printData()">打印数据</button>
<button (click)="clearData()">清空数据</button>
3.ts部分源码
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:'',
})
})
}
}