Javascript 在angular2中切换如何在内部工作
通过查阅一些参考资料,我在Angular2中创建了一个递归树,我在模板中得到了toggle属性,我没有在使用的模型中声明任何toggle属性或方法,但它仍然工作,有人能解释它是如何工作的吗Javascript 在angular2中切换如何在内部工作,javascript,angular,Javascript,Angular,通过查阅一些参考资料,我在Angular2中创建了一个递归树,我在模板中得到了toggle属性,我没有在使用的模型中声明任何toggle属性或方法,但它仍然工作,有人能解释它是如何工作的吗 <li *ngFor="let childNode of taxonomyChildList"><input *ngIf="childNode.hasMoreChildren" type="checkbox" data-md-icheck (click)="
<li *ngFor="let childNode of taxonomyChildList"><input
*ngIf="childNode.hasMoreChildren"
type="checkbox" data-md-icheck
(click)="childNode.toggle=!childNode.toggle" />
<a
*ngIf="!childNode.hasMoreChildren" (click)="records()">
{{childNode.dname
}}</a> <label *ngIf="childNode.hasMoreChildren">
{{childNode.dname}}</label>
<app-childnodes *ngIf="childNode.toggle"
[startingNode]="childNode.traversalPath"></app-childnodes>
</li>
在这里,toggle不是对象或方法的定义属性,所以它的工作方式是这样的。在第一次执行时,
childNode.toggle
是未定义的,而undefined
是JavaScript认为的值
<li *ngFor="let childNode of taxonomyChildList"><input
*ngIf="childNode.hasMoreChildren"
type="checkbox" data-md-icheck
(click)="childNode.toggle=!childNode.toggle" />
<a
*ngIf="!childNode.hasMoreChildren" (click)="records()">
{{childNode.dname
}}</a> <label *ngIf="childNode.hasMoreChildren">
{{childNode.dname}}</label>
<app-childnodes *ngIf="childNode.toggle"
[startingNode]="childNode.traversalPath"></app-childnodes>
</li>
对falsy值求反的计算结果为true
constchildnode={};
console.log(childNode.toggle);//未定义
childNode.toggle=!childNode.toggle;
console.log(childNode.toggle);//真的
childNode.toggle=!childNode.toggle;
console.log(childNode.toggle);//false
JavaScript是一种动态语言。由于您尚未定义任何toggle
属性,childNode.toggle
最初是未定义的,未定义的是falsy
做
childNode.toggle=!childNode.toggle
第一次添加一个切换
属性,该属性等于!未定义
,由于未定义是错误的,切换现在为真。再次单击会使其变为错误
请注意,使用AOT编译器构建应用程序时会出现编译错误,因为模板随后将编译为TypeScript,然后再编译为JavaScript,TypeScript随后会抱怨节点上没有toggle
属性(除非其类型为any
)。因此,您应该声明此toggle
属性
还要注意,Angular的当前版本是5.x。你不应该再使用Angular 2了