簡體   English   中英

綁定到ngFor中子組件的屬性時出現循環依賴性錯誤

[英]Cyclic dependency error when Binding to properties of child component in ngFor

我正在嘗試綁定到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" >&#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

任何人都可以在角度2中闡明它為什么抱怨/修復,和/或更好的方法嗎?

正如阿米特(Amit)指出的那樣,我得到的錯誤是由於將private parent: MenuItemComponent傳遞給MenuItemComponent構造函數(它是自己的構造函數)而產生的。

我錯誤地認為依賴注入器會為其創建一個不同的引用/實例並在那里停止,但是事實證明它正在創建一個無限循環。

在此階段,我仍然沒有找到更好的解決方案來解決如何使用組件/子組件在角度為2的子菜單中實現子菜單的問題,因此歡迎有更好解決方案的任何人添加答案,但是此答案解決了錯誤直。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM