javascript - 绑定(bind)到 ngFor 中子组件的属性时出现循环依赖错误

标签 javascript angularjs angular typescript ngfor

我正在尝试绑定(bind)到 ngFor 循环内的子组件上的输入属性以创建菜单结构。 我在搜索中找不到任何可以提供帮助的内容,因此我发布了这个问题。

我将菜单结构存储在 sidebar 组件中的代码中,作为 MenuItemComponents -> MenuStructure

sidebar.component.ts:(父组件)

export class SidebarComponent implements AfterViewInit {

  MenuStructure: MenuItemComponent[] = [];

  ngAfterViewInit() {
    //Define and Add Dashboard
      var dashboard = new MenuItemComponent(null);
      dashboard.title = 'Dashboard';
      dashboard.iconName = 'dashboard';

    //Define Documentation
      var documentation = new MenuItemComponent(null);
      documentation.title = 'Documentation';
      documentation.iconName = 'insert drive file';

    this.MenuStructure.push(dashboard);
    this.MenuStructure.push(documentation);
  }
}

这是子组件(也称为菜单的构建 block ):

菜单项.component.ts:

@Component({
  selector: 'app-menu-item',
  templateUrl: './menu-item.component.html',
  styleUrls: ['./menu-item.component.css']
})
export class MenuItemComponent implements OnInit {
  @Input() iconName: string;
  @Input() title: string;
  @Input() children: MenuItemComponent[] = [];
  @Input() routeLink: string = '';

  constructor(private parent: MenuItemComponent) { }

menu-item.component.html:

<a><i class="material-icons">{{iconName}}</i><span>{{title}}</span>
    <i class="material-icons" >&#xE313;</i> 
</a>

上面的模板用于侧边栏模板中的 ngFor 循环...

sidebar.component.html:

  <ul>
    <li *ngFor="let item of MenuStructure">
        <app-menu-item [title]='item.title' [iconName]='item.iconName'>
        </app-menu-item>
    </li>
  </ul>

但是,当尝试实现此操作时,我收到以下模板错误:

Template parse errors:
Cannot instantiate cyclic dependency! MenuItemComponent ("<ul>
        <li *ngFor="let item of MenuStructure">
            [ERROR ->]<app-menu-item [title]='item.title' [iconName]='item.iconName'>
            </app-menu-item>
      "): SidebarComponent@9:12

任何人都可以阐明为什么它会提示/修复,和/或在 Angular 2 中执行此操作的更好方法吗?

最佳答案

正如 Amit 所指出的,我收到的错误是通过将 privateparent: MenuItemComponent 传递到 MenuItemComponent 构造函数(它自己的构造函数)而生成的。

我错误地认为依赖注入(inject)器会为其创建一个不同的引用/实例并在那里停止,但事实证明它正在创建一个无限循环。

现阶段,我仍然没有找到关于如何使用组件/子组件在 Angular 2 中实现带有子级的菜单的更好解决方案,因此欢迎任何有更好解决方案的人添加答案,但是这个答案直接解决错误。

关于javascript - 绑定(bind)到 ngFor 中子组件的属性时出现循环依赖错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236454/

相关文章:

javascript - 如何在小滚动条中给 div 元素一个百分比高度?

javascript - 客户端 javascript 和 C++ 套接字服务器之间的通信

javascript - 单独或一起检查属性是否有意义?

javascript - 尝试使用 moment 格式化日期变量并将其传递给 datetimepicker 这会导致不推荐警告

javascript - 如何在同一行/水平对齐 ReactJS 的 <button/> 和 &lt;input/>?

javascript - 更改传单开放街道 map 的中心

javascript - Angular 2 将数据从组件发送到服务

单击任何选项时关闭菜单的 JavaScript 或 CSS 函数

javascript - 图表数据缩放无法读取未定义的属性 'length'

angular - 为生产 'On Azure DevOps' 构建 Angular 项目时出错