Angular的响应式表单数组可以使用FormArray来实现,通过改变检测覆盖表单可以使用ChangeDetectionStrategy来设置。
首先,创建一个响应式表单数组:
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 {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
items: this.fb.array([])
});
}
get items(): FormArray {
return this.myForm.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
在模板中,你可以使用FormArray来渲染表单数组,并可以通过调用addItem和removeItem方法来添加或删除项:
要改变检测覆盖表单,你可以在组件中设置ChangeDetectionStrategy:
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponentComponent implements OnInit {
// ...
}
通过将ChangeDetectionStrategy设置为OnPush,你可以手动控制何时触发变更检测,以提高性能。