在Angular 7中,如果在表单中使用了数组项,可能会导致堆栈溢出错误。以下是一种解决方法:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
items: FormArray;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
items: this.fb.array([])
});
this.items = this.myForm.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
通过以上代码,我们可以动态地添加和删除表单数组项,同时避免了堆栈溢出错误。