Search code examples
angularangular-materialangular-material2angular-cdk

AngularMaterial vertical stepper with cdkDropList issue with form input names


I'm doing a dropList with angular material, and I have the following problem:

Initialy: initialy

I'm using the index of the ngForm as the value for the attribute name of the form, if I change the position of the empty element at the end (moving with mouse) and then delete it I get this: second

Visually it works correctly, however if we look at the value of the ngForm fields we see that the values are not correct since the name has not been updated after deleting the element

One way to solve this is to put a Math.random in the name attribute, but this does not seem like nice solution

Any way to solve this problem?

https://stackblitz.com/edit/angular-hipzr9


Solution

  • If you console.log your event.container.data and your this.form.contactFormSections during your drop method, you will see they both match after your drag and drop in the list.

    drop(event: CdkDragDrop<string[]>) {
        moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    
        console.log(event.container.data);
        console.log(this.form.contactFormSections);
      }
    

    Where your logic is getting "decoupled" is because you are using template driven forms in your html #formBuild="ngForm"... this is an isolated form that is "decoupled" from the component

    You will need to leverage reactive forms to solve this problem. Build the FormGroup based on your sections and manipulate the form group, this will keep your underlying array "coupled" with the view and keep everything in sync.

    https://angular.io/guide/reactive-forms

    Detailed explanation of how to use dynamic reactive forms and submit a value from it.

    Dynamic form using *ngFor and submitting values from it