簡體   English   中英

FormArray Angular 中的動態 id

[英]Dynamic id in FormArray Angular

一切安好? 我正在使用 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
}

並創建一個函數,該函數返回一個帶有 formArray 值的 FormGroup

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()))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM