angular - Angular 2 Reactive Forms - How to show the FormArray controls different than input element
问题描述
I'm trying to use FormArray
with elements other than input
element. Most of the examples I've seen uses input
element as the dynamically presented objects.
In the component I've added the FormArray
.
newHobby: string = null;
employmentForm: FormGroup;
ngOnInit() {
this.userForm = new FormGroup({
'hobbies': new FormArray([])
});
}
onAddHobby() {
const control = new FormControl(this.newHobby, Validators.required);
(<FormArray>this.employmentForm.get('hobbies')).push(control);
}
And in the html,
<form [formGroup]="userForm">
<div class="form-group" formArrayName="hobbies">
<input type="text" id="new-hobby" class="form-control" [(ngModel)]="newHobby" [ngModelOptions]="{standalone: true}">
<button class="btn btn-outline-secondary btn-sm mt-3" type="button" (click)="onAddHobby()">Add Hobby</button>
<ul class="list-group">
<li class="list-group-item"
*ngFor="let hobbyControl of userForm.get('hobbies').controls; let i = index"
[formControlName]="i" [innerHtml]="hobbyControl[i]"></li>
</ul>
</div>
</form>
But whenever I'm trying to add a hobby, by clicking the Add Hobby
button I'm seeing the following error.
Can you please point out, where am I doing wrong. Or FormArray
does not support controls other than input
.
解决方案
如果您只想显示值,请使用“值”。您可以使用
<li class="list-group-item"
*ngFor="let hobbyControl of userForm.get('hobbies').controls; let i = index"
[formControlName]="i" [innerHtml]="hobbyControl[i].value"></li>
但你也可以使用
<li class="list-group-item"
*ngFor="let hobbyValue of userForm.get('hobbies').value; let i = index"
[innerHtml]="hobbyValue"></li>
看到 userForm.get('hobbies').value 是一个数组
推荐阅读
- gcc - 如何使用 onjcopy 复制所有 .rodata 部分?
- if-statement - 批处理文件比较 1 个本地和 1 个网络文件夹,如果它们匹配,则将本地复制到另一个本地
- python - Python中的溢出错误
- excel - 如何在工作表参考公式(谷歌表格)中包含过滤器?
- java - 我试图获得一维和二维数组的平均值。我得到了 1D 和 2D 的代码,但它没有为 2D 打印任何东西。我做错了什么?
- java - Java - 从 Windows 网络路径复制文件夹
- xcode - 无法在真实设备上启动应用程序 - Xcode 显示内存损坏
- excel - 在共享点中托管带有 ODBC 链接的 excel 文件
- python - 如何以较小的平均值按顺序获取价值
- swiftui - 使用 SwiftUI 等间距的圆形分割