簡體   English   中英

綁定到模板參考變量內部 <ng-container> 角

[英]Bind to Template Reference Variable inside <ng-container> angular

我有以下標記:

<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復選框時,希望以下行中的復選框也被選中。 我認為checkboxes上的[checked]="chkAll?.checked"可以解決問題,但不起作用。

是我的Stackblitz

由於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;
  });
}

有關演示,請參見此堆疊閃電戰

執行此操作的另一種方法如下:

在您的模板中:

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM