Search code examples
angularangular-reactive-formsangular-formsdragulang2-dragula

ReactiveForm element show different <select> value in drag ghost with Dragula


When there is an Angular ReactiveForm element inside a dragged element, it shows a changed value in the drag ghost. The element on its final destination shows the correct value again.

Try a minimum example on StackBlitz: When you grab the second element (O2 with value "O2") and drag it, the ghost changes its value to "O1" while being dragged.

Is it wrong to have a form element inside a draggable? If not, is it a bug? In ng2-dragula or rather in the (Reactive)FormsModule?

How could I work around this?


Solution

  • The problem is that selected option element must have selected attribute present.

    So, you might do this:

    add element reference, and also add change listener on select element, and then, on change, assign selected value to a variable which will then serve to set selected attribute via attr.selected in the template:

    Try this:

    <select [formControl]="formControl" (change)="chng($event)" #select>
      <option value="O1" [attr.selected]="selected === 'O1' ? '' : null">O1</option>
      <option value="O2" [attr.selected]="selected === 'O2' ? '' : null">O2</option>
      <option value="O3" [attr.selected]="selected === 'O3' ? '' : null">O3</option>
    </select>
    
    @ViewChild('select') select!: ElementRef<HTMLSelectElement>;
    
      selected: string = 'O2';
    
      formControl = new UntypedFormControl('O2');
    
      // set value for selected attribute
      chng(event: Event) {
        this.selected = (event.target as HTMLOptionElement).value;
      }
    

    Stackblitz demo