在Angular 8中,可以通过在响应式表单中使用FormArray来动态添加行。
首先,在组件的HTML模板中,添加一个按钮来触发添加行的操作:
然后,在组件的TS文件中,定义一个FormArray来存储动态添加的行:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
rows: this.fb.array([])
});
}
get rows() {
return this.form.get('rows') as FormArray;
}
addRow() {
this.rows.push(this.fb.control(''));
}
}
接下来,在组件的HTML模板中,使用*ngFor指令来循环显示表单行:
现在,当用户按下回车键时,可以调用addRow()方法来添加一行。
这样,每次按下回车键时,Angular 8响应式表单就会自动添加一行。