【问题标题】:Dynamic id in FormArray AngularFormArray Angular中的动态ID
【发布时间】: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>

【问题讨论】:

  • 为什么要使用(&lt;HTMLInputElement&gt;document.getElementById("category")).value 来获取值?为什么要使用(onChange)(blur) 来管理FormArray 中的更改?您正在使用 Angular 和响应式表单,因此订阅 valuesChanges(或至少使用 feedstockForm.value.feedstock[index].category
  • 嗨,Eliseo 没有使用 valuesChanges,因为我不能这样做,因为我使用的是表单数组
  • 使用 feedstockForm.value.feedstock[index].category,它甚至可以工作,但它没有用值初始化。

标签: javascript angular typescript


【解决方案1】:

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

所以,我们可以像这样创建表单组

this.feedstockForm=new FormGroup(
{
      new FormArray(data.map(x=>this.getCategoryGroup(x)
})

此外,要向 FormArray 添加一个新元素,您可以简单地(看看我们如何使用之前定义的两个函数

addElement(){
   this.categoryArray.push(this.getCategoryGroup()))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2020-08-05
    • 2019-11-23
    • 2018-05-20
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多