【发布时间】:2021-07-19 22:14:14
【问题描述】:
一切都好吗? 我正在使用 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>
【问题讨论】:
-
为什么要使用
(<HTMLInputElement>document.getElementById("category")).value来获取值?为什么要使用(onChange)和(blur)来管理FormArray 中的更改?您正在使用 Angular 和响应式表单,因此订阅 valuesChanges(或至少使用feedstockForm.value.feedstock[index].category) -
嗨,Eliseo 没有使用 valuesChanges,因为我不能这样做,因为我使用的是表单数组
-
使用 feedstockForm.value.feedstock[index].category,它甚至可以工作,但它没有用值初始化。
标签: javascript angular typescript