首页 > 解决方案 > 如何在Angular中突出显示使用CTRL +鼠标单击选择的多行

问题描述

我有一个一列的表。该表必须同时支持单行选择和多行选择,我想突出显示选定的行。

我使用 CTRL+ 鼠标单击选择了多行。

在 .html 文件中,

     <div class="card-body">
          <table class="table" >
            <tbody>

              <tr class="record" *ngFor="let item of staticData; let i = index" (click)="selectName( $event, item,i)" 
              [class.active]="i== selectedRow">
                <td>{{item.name}}</td>
              </tr>

            </tbody>
          </table>
        </div>

在 .ts 文件中,

    public selectName(event: any,item: any, i: number) {
    
    console.log(item);
    this.selectedRow= i;
    if(!event.ctrlKey)
    {
      this.singleName= item.name;
      console.log(this.singleName);
      this.nameArray=[];
     
    }
    else
    {
       this.addToArray(this.nameArray, item);
    }
    }

我可以使用上面的代码突出显示一行。如何突出显示选定的多行

标签: angular

解决方案


我建议不要在每个合作伙伴上使用一个属性,而不是保留一个单独的数组:

<tr class="record" *ngFor="let item of staticData; let i = index" (click)="selectPartner( $event, item,i)" 
          [class.active]="item.isSelected">
   <td>{{item.name}}</td>
</tr>

public selectPartner(event: any,item: any, i: number) {

    // Set a bool where you listen for ctrl key down so you can check against it here
    if (isCtrlKeyDown) {
      item.isSelected = !item.isSelected;
    }
    else {
      staticData.forEach((partner) => partner.isSelected = false);
      item.isSelected = true;
    }
}

然后让所有选定的合作伙伴只需做一个过滤器:

var selectedPartners = staticData.filter((partner) => partner.isSelected);

推荐阅读