[英]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.