[英]ERROR TypeError: _v.context.$implicit.toggle is not a function
I am testing a simple recursive Treeview component in angular4 using the below code. 我正在使用下面的代码在angular4中测试一个简单的递归Treeview组件。 But whenever I try to expand the children view on toggle()
. 但每当我尝试在toggle()
上展开子视图时。
I am getting an exception error: 我收到一个异常错误:
ERROR TypeError: _v.context.$implicit.toggle is not a function 错误TypeError:_v.context。$ implicit.toggle不是函数
Thanks 谢谢
tree-view.component.ts 树view.component.ts
export class TreeViewComponent implements OnInit {
constructor() { }
ngOnInit() {}
@Input() directories: Directory[];
}
tree-view.component.html 树view.component.html
<ul>
<li *ngFor="let dir of directories">
<label (click)="dir.toggle()"> {{ dir.title }}</label>
<div *ngIf="dir.expanded">
<tree-view [locations]="dir.children"></tree-view>
</div>
</li>
</ul>
Directory.ts Directory.ts
export class Directory{
title: string;
children: Directory[]
expanded = true;
checked = false;
constructor() {
}
toggle() {
this.expanded = !this.expanded;
}
getIcon() {
if (this.expanded) {
return '-';
}
return '+';
}
}
Like yurzui suggested, in case you are just typing your data, you don't have class instances, so the method toggle
isn't available. 与yurzui建议的一样,如果您只是键入数据,则没有类实例,因此方法toggle
不可用。 If you truly want to have your array with instances of your Directory
class, add the properties to constructor and when you get the data from api, create instances of your objects, so shortened version: 如果您真的想让您的数组包含Directory
类的实例,请将属性添加到构造函数中,当您从api获取数据时,创建对象的实例,以便缩短版本:
export class Directory {
title: string;
expanded: boolean;
constructor(title: string, expanded: boolean) {
this.title = title;
this.expanded = expanded
}
}
and in your api call: 在你的api电话中:
return this.httpClient.get<Directory[]>('url')
.map(res => res.map(x => new Directory(x.title, x.expanded)))
Now you have access to the toggle
method. 现在您可以访问toggle
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.