Search code examples
angularangular-materialangular-cdkangular-cdk-drag-drop

Angular FormArray Name Not Displaying For Drag & Drop


Trying to use cdkDragDrop populated by a FormGroup > FormArray. I can see the number of items in my array (3) is correctly rendered, but i cant display the value in the div, instead [Object Object] is displayed.

Component:

export class CdkDragDropSortingExample {

myForm: FormGroup;  

constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      title: ['title'],
      items: fb.array([
        fb.group({
          name: fb.control('1'),
          note: fb.control('quux')
        }),
        fb.group({
          name: fb.control('2'),
          note: fb.control('bar')
        }),
        fb.group({
          name: fb.control('3'),
          note: fb.control('baz')
        })         

      ])
    })
  }
  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.myForm.get('items').controls, event.previousIndex, event.currentIndex);
    moveItemInArray(this.myForm.get('items').value, event.previousIndex, event.currentIndex);
  }

HTML:

<form [formGroup]="myForm">
    <input formControlName="title" />
    <div cdkDropList
    class="example-list"
    (cdkDropListDropped)="drop($event)">

        <div [id]="i" class="example-box" *ngFor="let item of myForm.get('items').controls; let i=index;" cdkDrag
            #elem="cdkDrag" (mouseenter)="enter(i)">
            <span cdkDragHandle>drag {{item}}</span>            
        </div>
    </div>


    {{ myForm.value | json}}
</form>

Stackblitz:https://stackblitz.com/edit/angular-asevei-gf4der?file=app%2Fcdk-drag-drop-sorting-example.html


Solution

  • not really clear what you want to display in the div, but you're just interpolating a form group right now in this line:

    <span cdkDragHandle>drag {{item}}</span>  
    

    do you want something like

    <span cdkDragHandle>drag {{item.value | json}}</span>  
    

    or

    <span cdkDragHandle>drag {{item.value.name}}</span>  
    

    or maybe

    <span cdkDragHandle>drag {{item.get('name').value}}</span>