在< 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>
我想实现全选"功能.
如您所见,我在表标题中有一个条件,即如果标题名称等于某个值,则在该标题上添加一个输入.在表主体中,我还有一个条件,即是否应在该列中添加复选框
.
As you can see, I have the condition in the table header, that if the header name is equal to a certain value, add an input on that header. In the table body, I also have a condition, on whether there should be added an checkbox
to the column or not.
当我在表格标题中选择 #chkAll
复选框时,我希望也选中下面各行中的复选框.我认为复选框
上的 [checked] ="chkAll?.checked"
可以解决问题,但不起作用.
When I select the #chkAll
checkbox in the table header, I would like the checkboxes in the rows below, to also be selected. I thought that [checked]="chkAll?.checked"
on the checkboxes
would do the trick, but it does not work.
这里是我的Stackblitz
Here is my Stackblitz
推荐答案
由于 chkAll
变量是在单独的模板中定义的(由标头的 ngFor
循环创建)),在表格主体的标记中不可用.
Since the chkAll
variable is defined in a separate template (created by the ngFor
loop of the header), it is not available in the markup of the table body.
您可以在标题复选框的值更改时调用组件方法,以对行中的复选框执行选中/取消选中操作:
You can call a component method when the header checkbox value changes, to perform the check/uncheck of the checkboxes in the rows:
<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
方法使用 ViewChildren
提供的 QueryList
来访问复选框:
The checkAllBoxes
method uses the QueryList
provided by ViewChildren
to access the checkboxes:
@ViewChildren("chkBox") private chkBoxes: QueryList<ElementRef>;
checkAllBoxes(value: boolean) {
this.chkBoxes.forEach(chk => {
chk.nativeElement.checked = value;
});
}
有关演示,请参见此stackblitz .
这篇关于在< ng-container>内部绑定到模板参考变量角度的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!