【问题标题】:ERROR TypeError: _v.context.$implicit.toggle is not a function错误类型错误:_v.context.$implicit.toggle 不是函数
【发布时间】:2017-11-23 23:06:49
【问题描述】:

我正在使用以下代码在 angular4 中测试一个简单的递归 Treeview 组件。但是每当我尝试在toggle() 上扩展孩子们的视野时。

我收到异常错误:

ERROR TypeError: _v.context.$implicit.toggle 不是函数

谢谢

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>

目录.ts

 export class Directory{

      title: string;
      children: Directory[]
      expanded = true;
      checked = false;

  constructor() {

  }

  toggle() {
    this.expanded = !this.expanded;
  }

  getIcon() {
    if (this.expanded) {
      return '-';
    }
    return '+';
  }
}

【问题讨论】:

  • 如何创建Directory 实例?
  • 我做 api 调用并将其直接反序列化到目录:Directory[] 传递给树视图组件
  • 序列化不创建类实例。你只有对象数组
  • 嗯,有趣的任何建议如何解决?

标签: javascript angular typescript angular5


【解决方案1】:

就像 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

【讨论】:

  • 这似乎不适用于递归数组。我也尝试包含 children 属性,但问题仍然存在
  • 你能不能展示一下你现在所做的尝试,这给你带来了麻烦。
  • 嗨,我确实实现了您提供的代码。我的映射没有错误,但是当我单击切换功能时,上述异常仍然存在。
  • 你班上的children:Directory[] 属性是什么?对我来说似乎不正确?
  • 我的课堂上也有错误,但现在已修复,我添加了一个演示,所以它应该可以工作。但仍然想知道 Directory 类中的 Directory 数组在您的 Directory 类中:) 如果它是某个类的数组,您也需要创建该类的实例。
猜你喜欢
  • 2018-04-28
  • 2019-02-14
  • 2021-10-02
  • 2021-10-30
  • 2018-11-22
  • 2017-10-12
  • 2020-06-05
  • 2023-03-15
  • 2018-10-21
相关资源
最近更新 更多