Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR TypeError: _v.context.$implicit.toggle is not a function

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 image 796
Jim Avatar asked Dec 24 '22 12:12

Jim


1 Answers

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.

StackBlitz

like image 95
AT82 Avatar answered Jan 21 '23 19:01

AT82