Привязать к ссылочной переменной шаблона внутриугловая - PullRequest
0 голосов
/ 25 сентября 2018

У меня есть следующая разметка:

<table>
  <thead>
    <th *ngFor="let column of columnNames">
      <ng-container *ngIf="column === 'Column6'; else normalColumns">
        {{column}} <input type="checkbox" #chkAll />
      </ng-container>
      <ng-template #normalColumns>
        {{column}}
      </ng-template>
    </th>
  </thead>
  <tbody>
    <tr>
      <td *ngFor="let model of columnValues">
        <ng-container *ngIf="model === 'Value6'; else normal">
        {{model}} <input type="checkbox" [checked]="chkAll?.checked" />
      </ng-container>
      <ng-template #normal>
        {{model}}
      </ng-template>
      </td>
    </tr>
  </tbody>
</table>

Я хотел бы реализовать функцию «Выбрать все».

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

Когда я устанавливаю флажок #chkAll в заголовке таблицы, мне бы хотелось, чтобыфлажки в строках ниже, которые также будут выбраны.Я думал, что [checked]="chkAll?.checked" на checkboxes сделает трюк, но это не работает.

Здесь - мой Stackblitz

Ответы [ 2 ]

0 голосов
/ 25 сентября 2018

Другой способ сделать это следующим образом:

В вашем шаблоне:

<table>
  <thead>
    <th *ngFor="let column of columnNames">
      <ng-container *ngIf="column === 'Column6'; else normalColumns">
        {{column}} <input type="checkbox" #chkAll ngModel (change)="checkAll = chkAll.checked" />
      </ng-container>
      <ng-template #normalColumns>
        {{column}}
      </ng-template>
    </th>
  </thead>
  <tbody>
    <tr>
      <td *ngFor="let model of columnValues">
        <ng-container >
        {{model}} <input type="checkbox" [(checked)]="checkAll" />
      </ng-container>
      <ng-template #normal>
        {{model}}
      </ng-template>
      </td>
    </tr>
  </tbody>
</table>

В вашем компоненте:

Создайте логическое значение с именем checkAll.

Здесь Stackblitz

0 голосов
/ 25 сентября 2018

Поскольку переменная chkAll определена в отдельном шаблоне (созданном циклом ngFor заголовка), она не доступна в разметке тела таблицы.

Вы можете вызватьметод компонента, когда значение флажка заголовка изменяется, чтобы выполнить проверку / снятие флажка флажков в строках:

<table>
  <thead>
    <th *ngFor="let column of columnNames">
      <ng-container *ngIf="column === 'Column6'; else normalColumns">
        {{column}} <input type="checkbox" ngModel (ngModelChange)="checkAllBoxes($event)" />
      </ng-container>
      ...
    </th>
  </thead>
  <tbody>
    <tr>
      <td *ngFor="let model of columnValues">
        <ng-container *ngIf="model === 'Value6'; else normal">
          {{model}} <input type="checkbox" #chkBox />
        </ng-container>
        ...
      </td>
    </tr>
  </tbody>
</table>

Метод checkAllBoxes использует QueryList, предоставленный ViewChildren для доступа к флажкам:

@ViewChildren("chkBox") private chkBoxes: QueryList<ElementRef>;

checkAllBoxes(value: boolean) {
  this.chkBoxes.forEach(chk => {
    chk.nativeElement.checked = value;
  });
}

См. этот стек для демонстрации.

...