Как отсортировать таблицу с выпадающим списком выбрать по щелчку в угловой?

#javascript #html #angular #typescript #angular-material

Вопрос:

Вот данные, подобные приведенным ниже, как показано на рисунке, который я получаю.

введите описание изображения здесь

Но здесь я хочу отсортировать таблицу с выпадающим списком сортировки, выберите. Когда я выбираю элемент из списка и нажимаю «Применить», я хочу отсортировать таблицу по выбранному столбцу.

введите описание изображения здесь

Вот Мой resource.component.html

 <section class="dashboard-content">
<div class="table-content box-style">
    <div class="table-heading">
        <h3 style="font-weight: 700;">Resources</h3>
        <div class="search-form-wrapper">
          <div class="filter-list more-dropown">
            <div class="action-icon" mat-button [matMenuTriggerFor]="filter_menu">
              <span class="material-icons">sync_alt</span>
              <span class="filter-text">Sort By <span class="material-icons">expand_more</span></span>
            </div>
            <mat-menu #filter_menu="matMenu" (click)="$event.stopPropagation();">
              <ul class="filter-list-menu">
                <li *ngFor="let selectedM of selectedMenu; let i = index" class="custom-radio" (click)="$event.stopPropagation();">
                  <label (click)="$event.stopPropagation();">
                    <input type="radio" name="filterName" value="{{selectedM.name}}">
                    <span>{{selectedM.name}}</span>
                  </label>
                </li>
              </ul>
              <div class="filter-apply">
                <button mat-button class="btn-style sm-btn black-btn">Apply</button>
                <button mat-button class="btn-style sm-btn" routerLink="/resources">Reset All</button>
              </div>
            </mat-menu>
          </div>
        </div>
    </div>
    <div class="table-wrapper">
      <table mat-table [dataSource]="dataSource | paginate: {itemsPerPage: per_page, totalItems: total, currentPage: current_page }" matSort class="w-100 table-style">
          <ng-container matColumnDef="createdBy">
              <th mat-header-cell *matHeaderCellDef > Created by </th>
              <td mat-cell *matCellDef="let element" style="padding: 0px;white-space: nowrap;"> <span style="border-left: 5px solid {{element.categoryColor}};display:flex;padding: 19px 10px 19px 24px;vertical-align: top;height:100%;align-items: center;">{{element.createdByFName}} {{element.createdByLName}} </span></td>
          </ng-container>
            <ng-container matColumnDef="divisonName">
              <th mat-header-cell *matHeaderCellDef > Division Name </th>
              <td mat-cell *matCellDef="let element" style="height: 100%;white-space: nowrap;">{{element.divisonName}}</td>
          </ng-container>
          <ng-container matColumnDef="resourceName">
              <th mat-header-cell *matHeaderCellDef > Name </th>
              <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.resourceName}}</td>
          </ng-container>
          <ng-container matColumnDef="categoryName">
              <th mat-header-cell *matHeaderCellDef > Category </th>
              <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.categoryName}}</td>
          </ng-container>
          <ng-container matColumnDef="rType">
              <th mat-header-cell *matHeaderCellDef > Type  </th>
              <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{(getResourceType(element.rType))}}</td>
          </ng-container>
          <ng-container matColumnDef="resourceStatus">
              <th mat-header-cell *matHeaderCellDef > Assign Status</th>
              <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.resourceStatus}}</td>
          </ng-container>

          <ng-container matColumnDef="email">
            <th mat-header-cell *matHeaderCellDef > Email</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.email}}</td>
          </ng-container>

          <ng-container matColumnDef="phone">
            <th mat-header-cell *matHeaderCellDef > Phone</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.phone}}</td>
          </ng-container>

          <ng-container matColumnDef="lwd">
            <th mat-header-cell *matHeaderCellDef > LWD</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.lwd | date : "MM/dd/yyyy"}}</td>
          </ng-container>


          <ng-container matColumnDef="demob">
            <th mat-header-cell *matHeaderCellDef > Demob</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.demob | date : "MM/dd/yyyy"}}</td>
          </ng-container>

          <ng-container matColumnDef="release">
            <th mat-header-cell *matHeaderCellDef > Release</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;" > {{element.release | date : "MM/dd/yyyy"}}</td>
          </ng-container>

          <ng-container matColumnDef="request">
            <th mat-header-cell *matHeaderCellDef > Request</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.request}}</td>
          </ng-container>

          <ng-container matColumnDef="als">
            <th mat-header-cell *matHeaderCellDef > ALS</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{(element.als === 1) ? "Yes" : "No"}}</td>
          </ng-container>

          <ng-container matColumnDef="hours">
            <th mat-header-cell *matHeaderCellDef > Hours</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.hours}} Hours</td>
          </ng-container>

          <ng-container matColumnDef="leader">
            <th mat-header-cell *matHeaderCellDef > Leader</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.leader}}</td>
          </ng-container>

          <ng-container matColumnDef="personnel">
            <th mat-header-cell *matHeaderCellDef > Personnel</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.personnel}}</td>
          </ng-container>

          <ng-container matColumnDef="reportingLocation">
            <th mat-header-cell *matHeaderCellDef > Reporting Location</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.reportingLocation}}</td>
          </ng-container>

          <ng-container matColumnDef="dropOff">
            <th mat-header-cell *matHeaderCellDef > Drop Off</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.dropOff}}</td>
          </ng-container>

          <ng-container matColumnDef="pickUp">
            <th mat-header-cell *matHeaderCellDef > Pick Up</th>
            <td mat-cell *matCellDef="let element" style="white-space: nowrap;"> {{element.pickUp}}</td>
          </ng-container>

          <ng-container matColumnDef="view_more" >
              <th mat-header-cell *matHeaderCellDef style="max-width: 120px;width: 120px;min-width: 120px;"> View Details </th>
              <td mat-cell *matCellDef="let element" style="max-width: 120px;width: 120px;min-width: 120px;">
                  <button class="btn-style light-red-btn sm-btn" routerLink="/resources/full-view-resource/{{element._id}}">View more</button>
              </td>
          </ng-container>
          <ng-container matColumnDef="action">
              <th mat-header-cell *matHeaderCellDef class="text-center" style="max-width: 90px;width: 90px;min-width: 90px;"> Actions </th>
              <td mat-cell *matCellDef="let element; let i = index; " class="text-center" style="max-width: 90px;width: 90px;min-width: 90px;">
                  <span mat-button [matMenuTriggerFor]="edit_comm" class="action-icon"><span class="material-icons">more_horiz</span></span>
                  <mat-menu #edit_comm="matMenu">
                      <button mat-menu-item routerLink="/resources/add-edit-resource/{{element._id}}">Edit</button>
                      <button mat-menu-item (click)="openSendDialog(element._id)">Send SMS</button>
                      <button mat-menu-item (click)="openEmailDialog(element._id)">Send Email</button>
                      <button mat-menu-item (click)="deleteResource(element._id, i, $event)">Delete</button>
                  </mat-menu>
              </td>
          </ng-container>
          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let element; columns: displayedColumns;"></tr>

        </table>
    </div>
  <div class="text-center" *ngIf="dataSource amp;amp; dataSource.length == 0">
    <div class="text-muted font-medium-2 p-2">No Data Available</div>
  </div>
  <pagination-controls *ngIf="dataSource amp;amp; dataSource.length > 0" class="my-pagination" (pageChange)="handlePage($event)"></pagination-controls>
</div>
 

Здесь Мой ресурс.компонент.ts

 import { Component, OnInit, ViewChild } from '@angular/core';
import {SPMessageService} from '../../service/SPMessageService';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { PopupReferencesComponent } from '../popup/popup-references/popup-references.component';
import { PopupSendSmsComponent } from '../popup/popup-send-sms/popup-send-sms.component';
import {PopupUploadResourceComponent} from '../popup/popup-upload-resource/popup-upload-resource.component';
import {DNApiService} from '../../service/DNApiService';
import swal from 'sweetalert2'
import {PopupSendEmailComponent} from '../popup/popup-send-email/popup-send-email.component';
import {Subject} from 'rxjs';
import {PopupConfirmDeleteComponent} from '../popup/popup-confirm-delete/popup-confirm-delete.component';
import {DNHelper} from '../../service/DNHelper';
import {debounceTime} from 'rxjs/operators';
declare var angular: any;

@Component({
  selector: 'app-resources',
  templateUrl: './resources.component.html',
  styleUrls: ['./resources.component.scss']
})

export class ResourcesComponent implements OnInit {

displayedColumns: string[] = [];
dataSource: any;

resultsLength = 0;

public current_page = 0;
public per_page = 50;
public total = 0;
public requestPara = {};
public filter: any;
private subject: Subject<string> = new Subject();
menuUserType: any = "";
selectedMenu: any = [{}];
selectRedirect : any

constructor(private messageService: SPMessageService,
            public dialog: MatDialog,
            public apiService: DNApiService,
            public helper: DNHelper) {
  this.messageService.sendMessage(false);
  this.bindTableCol();

  if (DNHelper.loginUserData amp;amp; DNHelper.loginUserData.resourcePreference1 amp;amp; DNHelper.loginUserData.resourcePreference1.length > 0) {
    const selectedMenu = JSON.parse(JSON.stringify(DNHelper.loginUserData.resourcePreference1));
    this.selectedMenu = selectedMenu.filter((item:any) => item.show);
  }
}

ngAfterViewInit() {
}

ngOnInit(): void {
  this.getResourceList({page: 1});
  this.subject.pipe(debounceTime(500)).subscribe(searchTextValue => {
    this.applyFilter(searchTextValue);
  });

}

ngOnDestroy(): void {
  // Unsubscribe from all subscriptions
  this.subject.next();
  this.subject.complete();
}

onKeyUp(event: any){
  this.current_page = 1;
  this.subject.next(event.target.value);
}

applyFilter(filterValue: string) {
  if (filterValue) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
  }
  this.filter = filterValue;
  this.requestPara = {
    searchWord: filterValue,
    per_page: this.per_page,
    page: this.current_page
  };
  this.getResourceList(this.requestPara);
}

getResourceList(req: any): any {
  this.helper.toggleSidebarVisibility(true);
  this.apiService.listResource(req).subscribe((data: any) => {
    this.helper.toggleSidebarVisibility(false);
    let totalRecords = 0;
    if(data.data amp;amp; data.data.totalRecords amp;amp; data.data.totalRecords.length > 0) {
      totalRecords = data.data.totalRecords[0].count;
      //console.log("totalRecords", totalRecords);
      }
    this.dataSource = data.data.list;
    this.total = totalRecords;

    //console.log("this.total", this.total);
  }, err => {
    this.helper.toggleSidebarVisibility(false);
    //this.toastr.error(err, 'Error');
  });
}

deleteResource(id: any, index: any, event: any): any {
  const dialogRef = this.dialog.open(PopupConfirmDeleteComponent, {
    width: '500px',
    data: {message: 'Are you sure you want to delete this resource?'}
  });
  dialogRef.afterClosed().subscribe(result => {
    if (result) {
      this.helper.toggleSidebarVisibility(true);
      this.apiService.deleteResource(id).subscribe(data => {
        this.requestPara = {
          searchWord: this.filter,
          page: this.current_page,
        };
        this.getResourceList(this.requestPara);
        swal.fire(
          'Deleted!',
          data.message,
          'success'
        );
      }, (err: any) => {
        swal.fire(
          'Error',
          err.error.message,
          'error'
        );
      });
    }
  });
}

downloadResourceData(): void {
  this.helper.toggleSidebarVisibility(true);
  //console.log('AAAAAAAAAAAAAAAA')
  this.apiService.downloadResource().subscribe(data => {
    //console.log('data', data);
    /*var anchor = angular.element('<a/>');
    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,'   encodeURI(data.url),
      target: '_blank',
      download: data.filename
    })[0].click();*/
    location.href = data.url;

    /*var a = document.createElement('a');
    a.href = 'data:attachment/csv;charset=utf-8;base64,'   encodeURI(data.url);
    a.target = '_blank';
    a.download = data.filename;
    document.body.appendChild(a);
    a.click();*/

    this.helper.toggleSidebarVisibility(false);
    swal.fire(
      '',
      data.message,
      'success'
    );
  }, (err: any) => {
    this.helper.toggleSidebarVisibility(false);
    swal.fire(
      'Error',
      err.error.message,
      'error'
    );
  });
}

handlePage(event: any): void {
  this.current_page = event;
  this.requestPara = {
    searchWord: this.filter,
    page: this.current_page
  };
  this.getResourceList(this.requestPara);
}

bindTableCol() : void {
  if(DNHelper.loginUserData amp;amp; DNHelper.loginUserData.resourcePreference1 amp;amp; DNHelper.loginUserData.resourcePreference1.length > 0){
    this.displayedColumns = DNHelper.getColumnTable(DNHelper.loginUserData.resourcePreference1);
    this.displayedColumns.push('view_more');
    this.displayedColumns.push('action');
  } else {
    this.displayedColumns = ['createdBy','divisonName', 'resourceName', 'categoryName', 'rType', 'view_more', 'action'];
  // this.displayedColumns = ['resourceName','divisonName', 'categoryName', 'rType', 'view_more', 'action'];
  }

  this.menuUserType = DNHelper.menuUserType;
  this.displayedColumns = DNHelper.permissionTableRow(this.menuUserType, this.displayedColumns);
}

openPreferencesDialog(): void {
  let that = this;
  const dialogRef = this.dialog.open(PopupReferencesComponent, {
    width: "600px",
    data: {name: "resource1"}
  });

  dialogRef.afterClosed().subscribe(result => {
    if (result.result) {
      that.bindTableCol();
    }
  });
}

openSendDialog(id: any): void {
  const dialogRef = this.dialog.open(PopupSendSmsComponent, {
    width: "413px",
    data: {id: id, name: "resource", message:"message"}
  });
}

openEmailDialog(id: any): void {
  const dialogRef = this.dialog.open(PopupSendEmailComponent, {
    width: "762px",
    height: "500px",
    data: {id: id, name: "resource"}

  });
}

openDownloadResourceDialog(): void {
  let that = this;
  const dialogRef = this.dialog.open(PopupUploadResourceComponent, {
    width: "413px"
  });

  dialogRef.afterClosed().subscribe(result => {
    //('result', result);
    if(result.result) {
      that.requestPara = {
        searchWord: that.filter,
        page: that.current_page,
      };
      this.getResourceList(that.requestPara);
    }
  });
}

openSendToAllSms(): void {
  const dialogRef = this.dialog.open(PopupSendSmsComponent, {
    width: "413px",
    data: {name: "resource", confTxtMessage: 'Are you sure you want to send this message to all resources?', sendAll: true}
  });
}

getResourceType(type: any): any {
  return type.reduce((a: any, o: any) => (a.push(o.type), a), []);
}
}
 

Я использовал переключатель для выбора, а после этого кнопку применить, которая будет сортировать конкретный столбец.

Я изо всех сил старался решить эту проблему, но не получал конкретных решений.