[英]ngIf is being checked before a template variable is set
My case statement is basically 我的案件陈述基本上是
I'm trying to do (this is within an ngFor if it matters): 我正在尝试做(这在ngFor内很重要):
<input *ngIf="data.isToggleable" #toggleCheckbox type="checkbox" [checked]="true" />
<ng-template [ngIf]="!data.isToggleable || (data.isToggleable && toggleCheckbox.checked)" [ngIfElse]="elseTemplate">
Problem is it says cannot read property .checked of undefined. 问题是它说无法读取未定义的.checked属性。 Because (I'm guessing) of something to do with the *ngIf I have there.
因为(我猜)与* ng有关(如果我在那里)。
I also tried: 我也尝试过:
<input *ngIf="data.isToggleable" #toggleCheckbox type="checkbox" [checked]="true" />
<ng-template [ngIf]="!data.isToggleable || (toggleCheckbox && toggleCheckbox.checked)" [ngIfElse]="elseTemplate">
and while that got rid of the error, no matter if I checked/unchecked the box, it wouldn't change what part of the ng-template was called. 并且尽管它消除了错误,但是无论我是否选中此框,都不会改变ng-template的哪个部分。 I'm not really sure why that didn't work which is why I was trying the first part of this post.
我不太确定为什么不起作用,这就是为什么我尝试了本文的第一部分。
Looking for a reason these aren't working or just any alternative. 寻找这些都不起作用的原因或任何其他选择。 Thanks!
谢谢!
*ngIf causes template variables on the same element or children to be 'lost in space', it doesn't exist at component init so nothing outside the *ngIf'ed element can refer to it. * ngIf导致同一元素或子元素上的模板变量“丢失在空间中”,它在组件初始化时不存在,因此* ngIf'ed元素之外的任何内容都无法引用它。 Using css instead to hide the input should fix this:
使用css代替隐藏输入应解决此问题:
<input [style.display]="data.isToggleable ? 'block' : 'none'" #toggleCheckbox type="checkbox" [checked]="true" />
I believe the issue is by using ngIf
on input element won't exists while you are referencing it in ng-template
我相信问题是通过在
ng-template
中引用它时在输入元素上使用ngIf
将不存在
so there are two ways of fixing it 所以有两种修复方法
Warp it in another element and move ngIf
on that element 将其扭曲到另一个元素中,
ngIf
在该元素上移动ngIf
<div *ngIf="data.isToggleable">
<input #toggleCheckbox type="checkbox" [checked]="true" />
<ng-template [ngIf]="!data.isToggleable || (data.isToggleable && toggleCheckbox.checked)" [ngIfElse]="elseTemplate">
</div>
adding another check in ng-template to check if toggleCheckbox
is defined 在ng-template中添加另一个检查以检查是否已定义
toggleCheckbox
<input *ngIf="data.isToggleable" #toggleCheckbox type="checkbox" [checked]="true" />
<ng-template [ngIf]="!data.isToggleable || (data.isToggleable && toggleCheckbox && toggleCheckbox.checked)" [ngIfElse]="elseTemplate">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.