1

I have a recursive angular template using Pipe. My problem is it only displays up to 2 level.

Pipe Converter

Here, recursively filter the data to find all children by parentid

@Pipe({ name: 'converter' })
export class ConverterPipe implements PipeTransform {
  transform(array: any[], parentId: string = "0"): any[] {
    return this.filterNodes(array, parentId);
  }
  filterNodes(array: any[], parentId: string): any[] {
    return array.filter((node) => { 
      return node.parent === parentId; 
    }).map((node) => {
      console.log("parentid > " + parentId)
      console.log(node)
      node["items"] = this.filterNodes(array, node.id); 
      return node;
    });
  }
}

HTML

Recursive template

  <ul>
    <li *ngFor="let item of mainmenu" >
      <a href="#" >{{ item.id }} {{ item.name }}</a>
      <ng-container *ngTemplateOutlet="List; context:{ $implicit: submenu , parentid: item.id, submenuclass:1 }"></ng-container>
    </li>
  </ul>
<ng-template #List let-items let-parentid="parentid", let-submenuclass="submenuclass">
    <ul>
        <li *ngFor="let item of items | converter: parentid">
          <a href="#">{{ item.id }} {{ item.name }} {{ parentid }}</a>
          <ng-container *ngTemplateOutlet="List; context:{ $implicit: submenu, parentid:item.id, submenclass:0}"></ng-container>
        </li>
    </ul>
</ng-template>

Typescript

Contains the data and 2 variables which separates the main menu from sub menu

  menu = [
    {
      "id": "32",
      "name": "System Admin",
      "parent": "0",
    },    {
      "id": "33",
      "name": "User Maintenance",
      "parent": "32",
    },
    {
      "id": "35",
      "name": "Back Office Users",
      "parent": "33",
    },
    {
      "id": "37",
      "name": "Portal Users",
      "parent": "33",
    },
    {
      "id": "36",
      "name": "Site Maintenance",
      "parent": "32",
    },
    {
      "id": "38",
      "name": "Sample",
      "parent": "35",
    },
    {
      "id": "39",
      "name": "Sample2",
      "parent": "35",
    }
  ];
  mainmenu;
  submenu;
  constructor() { }

  ngOnInit() {
    this.mainmenu = this.menu.filter( item => item.parent =="0")
    this.submenu = this.menu.filter( item => item.parent !="0")
  }

The last two data, "Sample" and "Sample2" is not showing under "Back Office Users" when I run the app.

1 Answer 1

1

I have solved the problem, I should've put the submenu array variable under the recursive template parameter instead of the items under item. I also changed the third parameter to submenuclass since it conflicts with the variable. Please see my edit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.