1

我正在尝试使用角度材料拖放组件来重新排序基本无线电输入列表。

当页面加载时,会检查正确的无线电输入。我的问题是,当我使用 [Grab] 句柄重新排序列表中的选中项目时,单选选项似乎已重置,我无法弄清楚如何保留选择。

对我来说真正奇怪的是,如果这是一个复选框,它会正常工作。所以我假设这与我设置无线电输入的方式有关。

感谢您能够提供的任何帮助。

这是我的堆栈闪电战: https ://stackblitz.com/edit/angular-2q94xh

app.component.html

<table cdkDropList (cdkDropListDropped)="drop($event)">
  <tr *ngFor="let selection of content" cdkDrag>
    <td>
      <div class="grab" cdkDragHandle>[Grab]</div>
    </td>
    <td>
      <input 
        [id]="selection.id" 
        type="radio" 
        name="radio"
        [checked]="selection.selected"
      >
    </td>
    <td>{{ selection.selected }}</td>
  </tr>
</table>

app.component.ts

import { Component } from '@angular/core';
import {CdkDragDrop, moveItemInArray, transferArrayItem, CdkDrag} from '@angular/cdk/drag-drop';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.content, event.previousIndex, event.currentIndex);
  }
content = [
  {
    "id": "1",
    "selected": false
  },
  {
    "id": "2",
    "selected": false
  },
  {
    "id": "3",
    "selected": true
  }
]
}
4

1 回答 1

1

我认为这是 cdk/drag-drop 的问题。它不能正确处理拖动无线电组。

它为无线电输入创建具有相同名称的克隆。浏览器将选择移动到克隆的元素。

我为该错误创建了一个github 问题以及专门的 PR以解决该问题。

至于现在,我可以建议您以下解决方法:

import { DragRef } from '@angular/cdk/drag-drop';

function patchCloneNode(method) {
  const originalMethod = DragRef.prototype[method];

  DragRef.prototype[method] = function() {
    const sourceNode = this._rootElement;
    const originalRadioInputs = sourceNode.querySelectorAll('input[type="radio"]');
    
    const clonedNode = originalMethod.apply(this, arguments) as HTMLElement; 
    const clonedRadioInputs = clonedNode.querySelectorAll<HTMLInputElement>('input[type="radio"]');

    Array.from(clonedRadioInputs).forEach((input, i) => {
      input.name = originalRadioInputs[i].name + method;
    });
    return clonedNode;
  }   
} 

patchCloneNode('_createPlaceholderElement');
patchCloneNode('_createPreviewElement');

分叉的 Stackblitz

于 2020-08-07T16:59:31.343 回答