Как установить флажок по умолчанию в таблице mat для определенных строк в angular8 при модальном клике? - PullRequest
0 голосов
/ 26 февраля 2020

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

Первоначально, при нажатии кнопки Добавить позицию, я открываю диалоговое окно и формирую выбор таблицы соответствия, выбирая нужные элементы и после закрытия модального диалогового окна я добавляю обратно в другую таблицу матов то, что мы выбрали в модальном режиме, и когда мы нажимаем на те же самые элементы Добавить строку, необходимо выбрать ранее выбранные элементы. Может кто-нибудь дать мне знать, как это можно проверить на модальном открытии снова?

Вот видео захват для проверки вопроса https://share.vidyard.com/watch/XonduKJB8a9DsxYVWuj362

А также я пытался с this.selection.select (row);

Но это не проверено. Вот фрагмент кода для модального файла TS

this.selectedData.forEach(row => {
      console.log(row);
      this.selection.select(row);
    });

Ответы [ 2 ]

0 голосов
/ 26 февраля 2020

Надеюсь, это поможет ...

app.component.ts

displayedColumns: string[] = ['select', 'position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
selection = new SelectionModel<PeriodicElement>(true, []);

selectedData: any = [];


 isAllSelected() {
   const numSelected = this.selection.selected.length;
   const numRows = this.dataSource.data.length;
   return numSelected === numRows;
 }


 checkboxLabel(row?: PeriodicElement): string {
   if (!row) {
     return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
   }   
   return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row 
   ${row.position + 1}`;
  }

app.component. html

<div class="container">
  <form class="text-center" #form="ngForm">
    <div class="row">
      <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data- 
       target="#myModal">Open Modal</button>
    </div>

   <table>
     <thead>
       <tr>
      <th>No.</th>
      <th>Name</th>
      <th>Weight</th>
      <th>Symbol</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of this.selection.selected">
      <td>{{item.position}}</td>
      <td>{{item.name}}</td>
      <td>{{item.weight}}</td>
      <td>{{item.symbol}}</td>
    </tr>
  </tbody>
</table>

  </form>
</div>

<div id="myModal" class="modal fade" role="dialog">

<!-- Modal content-->
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Modal Header</h4>
  </div>
  <div class="modal-body">
    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

      <!-- Checkbox Column -->
        <ng-container matColumnDef="select">
          <th mat-header-cell *matHeaderCellDef>

          </th>
          <td mat-cell *matCellDef="let row">
            <mat-checkbox (click)="$event.stopPropagation()"
                          (change)="$event ? selection.toggle(row) : null"
                          [checked]="selection.isSelected(row)"
                          [aria-label]="checkboxLabel(row)">
            </mat-checkbox>
          </td>
        </ng-container>

        <!-- Position Column -->
        <ng-container matColumnDef="position">
          <th mat-header-cell *matHeaderCellDef> No. </th>
          <td mat-cell *matCellDef="let element"> {{element.position}} </td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="name">
          <th mat-header-cell *matHeaderCellDef> Name </th>
          <td mat-cell *matCellDef="let element"> {{element.name}} </td>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="weight">
          <th mat-header-cell *matHeaderCellDef> Weight </th>
          <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="symbol">
          <th mat-header-cell *matHeaderCellDef> Symbol </th>
          <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"
            (click)="selection.toggle(row)">
        </tr>
    </table>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
</div>

0 голосов
/ 26 февраля 2020

Сохраните в массиве чеки

Объявите в .ts

checks:boolean[]=[]

in. html используйте

<input type="check" [(ngModel)]="checks[i]">

И учтите, что когда вы даете отметьте все, что вам нужно, это

checks.forEach(x=>{x=true})
...