How to get index of changed item in angular form array

﹥>﹥吖頭↗ 提交于 2019-12-02 23:01:20

I would not use the valueChanges here, it would be fired excessively, specially if the array has many values.

You could have a change event on each value, and just pass the value and index, something like

(keyup)="changeValue(line.controls.ProductName.value, i)"

But this kind of fights the purpose of the reactive form.

Even though you have plenty of values that you do not want to show in form, and it is values that the user cannot modify, I'd just add them to the form anyway as form controls, nothing says that you need to show them in template!

This way, if you build the form in a way that it would match your model order, you could just directly assign the form value to your model upon submit. I highly recommend this approach.

export class CustomFormArray {
     public form: FormGroup;

     public get someArray(): FormArray {
          return this.form.get('someArray') as FormArray
     }

     constructor(private _fb: FormBuilder) {
          this.form = _fb.group({
               someArray: _fb.array([])
          });

          this.someArray.controls.forEach(
               control => {
                   control.valueChanges.subscribe(
                        () => {
                       console.log(this.someArray.controls.indexOf(control)) // logs index of changed item in form array
                        }
                   )
               }
          )
     }
}    

You can create an own component for the items that you want to maintain in your form array. For every update, delete etc. you emit an event to the parent component and the index you can either emit with the event that you bind on in the parent component or you have the index in the parent component in the template too to use it as additional input parameter for the function that you use to bind on the change event of the child component.

Read through this article and you will understand what I mean:

https://medium.com/spektrakel-blog/angular2-building-nested-reactive-forms-7978ecd145e4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!