I am testing a simple recursive Treeview component in angular4 using the below code. But whenever I try to expand the children view on toggle()
.
I am getting an exception error:
ERROR TypeError: _v.context.$implicit.toggle is not a function
Thanks
tree-view.component.ts
export class TreeViewComponent implements OnInit {
constructor() { }
ngOnInit() {}
@Input() directories: Directory[];
}
tree-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
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. 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:
export class Directory {
title: string;
expanded: boolean;
constructor(title: string, expanded: boolean) {
this.title = title;
this.expanded = expanded
}
}
and in your api call:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With