javascript - FormArray Angular中的动态ID
问题描述
一切安好?我正在使用 FormArray 并且遇到以下问题,当尝试获取类别的值时,它总是返回相同的值,因为它是一个 formArray,id="category" 是固定的。我目前可以像这样保持 id 动态:id:"category"+i。但是我没有因此得到这个 id:"category"+i 值。动态的。问题是如何动态地获取这个值。提前感谢
Component
getCategory() {
this.nameList = []
const value = (<HTMLInputElement>document.getElementById("category")).value
console.log(this.nameList)
this.initcategory(value)
}
initcategory(value) {
console.log(value)
const totalResults = 0;
const searchModel = {
text: '',
status: '',
};
this.feedstockService.getFeedstock(totalResults, searchModel)
.subscribe(response => {
const feedstocks = response.results.filter(x => x.category === value)
feedstocks.forEach(feedstock => this.nameList.push(feedstock.name))
})
}
HTML
<ng-container [formGroup]="feedstockForm">
<ng-container formArrayName="feedstock">
<accordion [closeOthers]="oneAtATime" *ngFor="let fcFeedStock of feedstockForm.get('feedstock')?.controls; let i = index">
<accordion-group heading="{{ fcFeedStock.get('position').value }} / {{ fcFeedStock.get('category').value }}" [formGroupName]="i">
<div>
<i class="material-icons close-category" (click)="removeFeedstockCategory(i)">
close
</i>
</div>
<div class="divide-section">
<div class="first-column">
<div class="header-section options">
<span>ADICIONAR COMPONENTE</span>
<i class="material-icons" (click)="addFeedstockComponent(i)">
add
</i>
</div>
<div class="form-group">
<label for="category">CATEGORIA</label>
<select class="form-control" formControlName="category" id="category" (onChange)="getCategory()" (blur)="onCountryChange($event.target.value)">
<option value="" selected ></option>
<option *ngFor="let cat of categories" [value]="cat.value">
{{cat.viewValue}}
</option>
</select>
</div>
解决方案
Rod,当我们管理 FormGruoup 的 FormArray 时(我想你想以这种方式管理一个数组
data=[{position:..category},{position:..,category:...}]
首先我们用数组做一个getter
get categoryArray()
{
return this.feedstockForm.get('feedstock') as FormArray
}
并创建一个返回 FormGroup 的函数,该函数具有 formArray 的值
getCategoryGroup(data:any=null)
{
data=data ||{position:0,category:''}
return new FormGroup({
position:new FormGroup(data.position),
category:new FormGroup(data.category)
})
}
看到这个函数返回一个 FormControls 的 FormGroup,它具有我们传递的对象“数据”的值,或者如果我们不传递参数,则返回一个空的 FormGroup
所以,我们可以像这样创建我们的 formGroup
this.feedstockForm=new FormGroup(
{
new FormArray(data.map(x=>this.getCategoryGroup(x)
})
此外,要向 FormArray 添加一个新元素,您可以简单地(查看我们在定义之前如何使用这两个函数
addElement(){
this.categoryArray.push(this.getCategoryGroup()))
}
推荐阅读
- javascript - Amchart 4:如何在单击条形图中的条形/列时突出显示条形/列
- asp.net - ASP.NET webAPI 框架缓慢问题
- python - Flask - 上传时的空文件
- python - 如何不在while循环中打印new_lines?
- cygwin - cygwin:无法访问网络驱动器
- html - 为什么我的容器高度不适合内容?
- sql - SQL通过将表1与表2中的2个条件匹配来选择表列
- visual-studio-code - 更改 VS Code 终端的默认工作目录
- file - 检查文件是否存在 20 小时前的 ansible
- java - 在 Java 中,可以使用“原始未参数化类”-es 而不是使用虚拟接口吗?