Angular 5中FormArray实现URL重复字段的数据绑定问题
解决Angular FormArray的URL输入字段数据绑定问题
嘿,这问题我熟!你遇到的核心点是FormArray里的控件需要用索引来做formControlName,因为FormArray是有序的控件集合,每个控件的标识就是它在数组里的位置索引。
第一步:修改HTML的formControlName
把你代码里的formControlName="???"改成用循环的索引i,推荐用方括号的属性绑定方式(更符合Angular的绑定规范):
<form [formGroup]="myForm"> <div class="form-row"> <div class="col mb-3"> <input type="text" class="form-control" formControlName="otherField"> </div> </div> <div class="form-row"> <div class="col mb-3" formArrayName="urls"> <div class="input-group" *ngFor="let item of urls.controls; let i = index" > <!-- 这里改成索引i的属性绑定 --> <input type="text" class="form-control" [formControlName]="i"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button" (click)="addUrl()"> <i class="fas fa-plus"></i> </button> </div> </div> </div> </div> </form>
第二步:确保getter方法正确
你的组件里的urls getter需要明确指定为FormArray类型,这样Angular才能正确识别它的controls:
get urls(): FormArray { return this.myForm.get('urls') as FormArray; } get otherField() { return this.myForm.get('otherField'); }
第三步:实现添加新URL的方法
既然你有个加号按钮,顺便给你补上添加新输入框的逻辑,在组件里加这个方法:
constructor(private fb: FormBuilder) {} // 初始化表单的代码保持不变 ngOnInit() { this.myForm = this.fb.group({ otherField: ['', Validators.required], urls: this.fb.array([ new FormControl('test'), new FormControl('test2') ]) }); } // 添加新的URL输入框 addUrl() { this.urls.push(this.fb.control('')); }
为什么这么做?
FormArray和FormGroup不同,FormGroup是用键值对存储控件,而FormArray是用有序数组存储,所以每个控件的“键”就是它的索引值。用[formControlName]="i"就能让Angular把当前输入框和FormArray中对应索引的FormControl绑定起来,这样数据就能正常双向同步啦!
内容的提问来源于stack exchange,提问作者NDDT
相关产品推荐
相关产品推荐

