我试图绑定到ngFor循环内的子组件上的输入属性,以创建菜单结构。
我无法在搜索中找到任何东西来提供帮助,因此我发布了这个问题。
我将菜单结构存储在侧边栏组件中的代码中,作为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);
}
}
这是子组件(也就是菜单的构建块):
menu-item.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" ></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
任何人都可以从角度2上了解为什么它抱怨/修复,和/或更好的方法吗?
最佳答案
正如阿米特(Amit)指出的那样,我得到的错误是通过将private parent: MenuItemComponent
传递给MenuItemComponent构造函数(它是自己的构造函数)而产生的。
我错误地认为依赖注入器会为其创建一个不同的引用/实例并在那里停止,但是事实证明它正在创建一个无限循环。
在这一阶段,我仍然没有找到更好的解决方案来解决如何使用组件/子组件来实现带有角度为2的子代的Menu的问题,因此欢迎有更好解决方案的任何人添加答案,但是此答案解决了错误直。