我正在使用以下代码在 angular4 中测试一个简单的递归 Treeview 组件。但是每当我尝试在 toggle()
上扩展 subview 时。
我遇到异常错误:
ERROR TypeError: _v.context.$implicit.toggle is not a function
谢谢
tree-view.component.ts
export class TreeViewComponent implements OnInit {
constructor() { }
ngOnInit() {}
@Input() directories: Directory[];
}
TreeView .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>
目录.ts
export class Directory{
title: string;
children: Directory[]
expanded = true;
checked = false;
constructor() {
}
toggle() {
this.expanded = !this.expanded;
}
getIcon() {
if (this.expanded) {
return '-';
}
return '+';
}
}
最佳答案
正如 yurzui 所建议的,如果您只是键入 您的数据,您没有类实例,因此方法toggle
不可用。如果你真的想让你的数组包含你的 Directory
类的实例,将属性添加到构造函数,当你从 api 获取数据时,创建你的对象的实例,所以缩短版本:
export class Directory {
title: string;
expanded: boolean;
constructor(title: string, expanded: boolean) {
this.title = title;
this.expanded = expanded
}
}
并在您的 api 调用中:
return this.httpClient.get<Directory[]>('url')
.map(res => res.map(x => new Directory(x.title, x.expanded)))
现在您可以访问 toggle
方法了。
StackBlitz
关于javascript - 错误 TypeError : _v. context.$implicit.toggle 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464337/