1

I've a form where user can drag selected img and drop it in target location and submit the form to backend.

Source data is Array of Object(API),

Issue:

  1. when drag one item and put it in drag location, the item gets multiplied / duplicated - (objects in array duplicated)
  2. when dragged item moved back to its original position, again it gets duplicated (objects in array duplicated)
  3. when when hit the submit form, its not only showing lot of duplicated items

Expectation:

drag and drop only selected items and submit the form.

ngOnInit() {
    this.initTestForm();
}

ngAfterViewInit() { }

initTestForm() {
    this.myTestForm = this.fb.group({
        //  myDivName: new FormControl(this.containerData),
        myDivName: new FormControl(this.containerData),
    });
}
drop(event: CdkDragDrop<Item[]>) {
    if(event.previousContainer === event.container) {
    moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
    );
} else {
    transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
    );

    console.log(
        'transferArrayItem',
        event.container.data[event.currentIndex]
    );
    this.addItem(event.container.data[event.currentIndex]);
}
}

get myDivName() {
    return this.myTestForm.get('myDivName') as FormArray;
}
addItem(item: any) {
    this.basket.push(item);
    this.myDivName.push(this.fb.control(item));
}
removeItem() {
    this.basket.pop();
    this.myDivName.removeAt(this.myDivName.length - 1);
}
savedata() {
    console.log(this.myTestForm);
}

stackblitz - issue reproduced

Since my scenarios is bit different, i couldn't find any solutions from SO

1 Answer 1

3

Finally, I fixed my issue by myself, by doing little modification like below.

initialize formControlName like myDivName: this.fb.array([]),

 get myDivName() {
    return <FormArray>this.myTestForm.get('myDivName');
  }

inside drop() method assign and pass formValue

const formArry = this.myDivName;
formArry.insert(0,this.fb.control(event.container.data));

working demo

Note: I'm not sure how efficient the fix is, but will optimize it as much as can.

Thanks to all who atleast view my question

Sign up to request clarification or add additional context in comments.

2 Comments

Try this to filter you final data source filter
really not (if you drop out you need remove not add). Use a FormControl and use this.myTestForm.get('myDivName').setValue(event.container.data). Yes a FormControl can store an array of object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.