在 Angular 表单中,当使用 Formarray 控件包含一组 FormGroup 时,如果需要对其中的 Select 控件进行索引控制,可以使用以下代码示例:
HTML 代码:
TypeScript 代码:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
formArray: this.fb.array([
this.fb.group({
mySelect: this.fb.control('first')
}),
this.fb.group({
mySelect: this.fb.control('second')
}),
this.fb.group({
mySelect: this.fb.control('third')
})
])
});
}
get formArray(): FormArray {
return this.form.get('formArray') as FormArray;
}
prevOption(select: any) {
const index = select.selectedIndex;
select.selectedIndex = index > 0 ? index - 1 : select.options.length - 1;
}
nextOption(select: any) {
const index = select.selectedIndex;
select.selectedIndex = index < select.options.length - 1 ? index + 1 : 0;
}
}
上述代码中,使用了两个按钮分别对应前一项和后一项,通过判断当前选中项的索引来进行控制。其中 prevOption 和 nextOption 方法均接收 Select 控件作为参数。
上一篇:AngularFormarrayLoadMultipleValue
下一篇:AngularFormControl的material-checkboxes.component有选定的值,但this.controlValue是一个空数组。