我正在尝试绑定(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" ></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/