How to create a “submenu” in a dynamic dropdown list with typescript and angular?

扶醉桌前 提交于 2021-02-10 05:14:33

问题


This is how I have created a dynamic dropdown list:

.html

<label> Move to </label>
    <select [(ngModel)] = "mSelectedCategoryNameMoveTo" 
            (click)     = "onMoveToSelected()" 
            [disabled]  = "mflagDisableMoveTo" >

        <option *ngFor = "let category of categories" [ngValue] = "category.name" >
            {{category.name}}
        </option>       

    </select>

Here the list categories is coming from .ts file. All the variables and the functions are defined in the corresponding .ts file.

The category structure .ts is as follows:

export interface CategoryStructure
{
    id:          number
    name:        string
    description: string 
    blogIds:     number[]
}

What would be the way to create a "submenu" here?

This is what a submenu looks like:


回答1:


Edit 2

Another live demo menu-style-related:
https://stackblitz.com/edit/angular-ivy-zrzfuy


Edit

Reactive Form Live Demo: https://stackblitz.com/edit/angular-ivy-fhvvzs


This is an example of how to do it.

File .html

<select id="categoriesList" name="categoriesList" [ngModel]="categorySelected"
(ngModelChange)="setAnotherSelect(+$event)">
    <option value="-1"></option>
    <option *ngFor="let category of categories" value="{{ category.id }}">{{ category.name }}</option>
</select>

<select id="randomElementsList" name="randomElementsList" [ngModel]="randomElements" *ngIf="showRandomElements">
    <option value="-1"></option>
    <option *ngFor="let element of randomElements" value="{{ element.id }}">{{ element.name }}</option>
</select>

File model.ts

export interface ICategoryStructure
{
    id: number;
    name: string;
    description: string;
    blogIds: number[];
}

File component.ts

import { ICategoryStructure } from './myApp.model'

public categories: ICategoryStructure[] = [
    { id: 1, name: 'test1', description: 'description1', blogIds: [1, 2] },
    { id: 2, name: 'test2', description: 'description2', blogIds: [3, 4] },
    { id: 3, name: 'test3', description: 'description3', blogIds: [5, 6] },
  ];
  public categorySelected: number = -1;

  public randomElements: ICategoryStructure[] = [];
  public randomElementSelected: number = -1;
  public showRandomElements = false;

  public setAnotherSelect(numberId) {
    this.categorySelected = numberId;
    this.showRandomElements = true;
    this.randomElements = [];
    switch (numberId) {
        case 1:
            this.randomElements = [
              { id: 4, name: 'test4', description: 'description4', blogIds: [7, 8] },
              { id: 5, name: 'test5', description: 'description5', blogIds: [9, 10] },
              { id: 6, name: 'test6', description: 'description6', blogIds: [11, 12] },
            ];
            break;
        case 2:
            this.randomElements = [
              { id: 7, name: 'test7', description: 'description7', blogIds: [13, 14] },
              { id: 8, name: 'test8', description: 'description8', blogIds: [15, 16] },
              { id: 9, name: 'test9', description: 'description9', blogIds: [17, 18] },
            ];
            break;
        case 3:
            this.randomElements = [
              { id: 10, name: 'test10', description: 'description10', blogIds: [19, 20] },
              { id: 11, name: 'test11', description: 'description11', blogIds: [21, 22] },
              { id: 12, name: 'test12', description: 'description12', blogIds: [23, 24] },
            ];
            break;
        default:
            this.showRandomElements = false;
            break;
    }
  }

Live demo here:
https://stackblitz.com/edit/angular-ivy-hzee7k




回答2:


The easiest would be to use the power of NgTemplateOutlet. So its gonna be something like this, with this approach it's gonna recursively create child tree:

export interface CategoryStructure
{
    id:          number
    name:        string
    description: string 
    blogIds:     number[]
    children:    CategoryStructure[]
}

and use it as follows:

<ng-template #itemTemplate let-items>
    <li *ngFor="let item of items">
        <a>{{ item.name }}</a>
        <ul class="submenu" *ngIf="item?.children?.length > 0">
            <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item.children }"></ng-container>
        </ul>
    </li>
</ng-template>
<!-- Parent category rendering -->
<ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: categories }"></ng-container>

To render the menu like you have its something like:

interface Item {
    name: string;
    icon?: string;
    route: string;
    children?: Item[];
}

// Component
public menu: Item[] = [
    {
        name: 'Parent 1',
        route: 'test',
        children: [
            {
                name: 'Child 1',
                route: 'test'
            },
            {
                name: 'Child 2',
                route: 'test'
            }
        ]
    },
    {
        name: 'Parent 2',
        route: 'test'
    },
]

// Template
<ul class="menu">
    <ng-template #menuRef let-items>
        <li *ngFor="let item of items">
            <a [routerLink]="item.route">
                <img [src]="item?.children?.length > 0 && !item.icon ? '/folder.png' : item.icon" />
                {{ item.name }}
            </a>
            <ul class="submenu" *ngIf="item?.children?.length > 0">
                <ng-container *ngTemplateOutlet="menuRef; context: { $implicit: item.children }"></ng-container>
            </ul>
        </li>
    </ng-template>
    <ng-container *ngTemplateOutlet="menuRef; context: { $implicit: menu }"></ng-container>
</ul>



回答3:


Hi I built an example for this problem I try to keep it as simple as I could, I think it handles the kind of submenu you wanted, a click on the > shows the submenus and click on the label of the submenu selects it

https://stackblitz.com/github/gabrielguerrero/stackoverflow-submenu?file=src%2Fapp%2Fcomponents%2Fmenu%2Fmenu.component.ts

I used cdk portal and templates to build it, the main logic is the menu component

I basically create a template for the submenu items, that I show in a cdk portal when you click on the arrow

<app-menu-item
  [item]="item"
  (showSubMenu)="showSubmenu($event)"
></app-menu-item>

<ng-template let-items>
  <div class="sub-items">
    <app-menu-item
      *ngFor="let item of items"
      [item]="item"
      (click)="selected.emit(item)"
      (showSubMenu)="showSubmenu($event)"
    ></app-menu-item>
  </div>
</ng-template>

This is the code to show the template:

showSubmenu(event: SubItemsEvent) {
  const positionStrategy = this.overlay
    .position()
    .flexibleConnectedTo(event.element)
    .withPositions([
      {
        originX: 'end',
        originY: 'top',
        overlayX: 'start',
        overlayY: 'top',
      },
    ]);
  const overlayRef = this.overlay.create({
    positionStrategy,
    hasBackdrop: true,
  });
  this.subItemsOverlays.push(overlayRef);
  const portal = new TemplatePortal(this.template, this.viewContainerRef, {
    $implicit: event.item.subItems,
  });
  overlayRef.attach(portal);
}

In case you don't know much about cdk overlay here is the best doc I could find of it https://netbasal.com/creating-powerful-components-with-angular-cdk-2cef53d81cea

There are many ways to implement this but I tried to make one very simple that will cover your needs



来源:https://stackoverflow.com/questions/61271254/how-to-create-a-submenu-in-a-dynamic-dropdown-list-with-typescript-and-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!