Search code examples
javascriptangularng-zorro-antd

Render ng-zorro tags from component


I'm trying to render a <li> with some ng-zorro tags, I try with innerHTML but when i enter to the page this fails, I want to show differents menu's if the user get in a specific application (route)

I have my JSON like this

menuApp = [
    {
      "app": "requerimientos",
      'menu': '\
          <li nz-menu-item nzMatchRouter>\
            <a routerLink="/applications/dashboard/requerimientos/crear-pedido">Crear pedido</a>\
          </li>\
          <li nz-menu-item nzMatchRouter>\
            <a routerLink="/applications/dashboard/requerimientos/verificar-pedido">Verificar pedido</a>\
          </li>\
      '
    }
  ]

and in my HTML

<li nz-submenu nzOpen nzTitle="Menú {{activeChild}}" nzIcon="appstore" *ngIf="activeChild != ''">
    <div *ngFor="let app of menuApp; index as i">
        <ul *ngIf="app.app === activeChild">
            <div [innerHTML]="app.menu"></div>
        </ul>
    </div>
</li>

but when i render the page the <li> print without any ng-zorro tag or class

html result

hope someone can help me


Solution

  • Angular doesn't work that way. Custom directives (like nzMatchRouter) cannot be shoehorned in with an innerHTML. You have to instruct the parser to compile the HTML after it's been added. But even still, there are more efficient, angular-centric methods you can use - like keeping your menu as a simple array of text/url values and using *ngFor to iterate them. That way the <li> directives are compiled at runtime

    menuApp = [
        {
          "app": "requerimientos",
          'menu': [
             {text: "Crear pedido", url: "/applications/dashboard/requerimientos/crear-pedido" },
             {text: "Verificar pedido", url: "/applications/dashboard/requerimientos/verificar-pedido" }
        ]}
    

    Then your HTML would be like

    <li nz-submenu nzOpen nzTitle="Menú {{activeChild}}" nzIcon="appstore" *ngIf="activeChild != ''">
        <div *ngFor="let app of menuApp; index as i">
            <ul *ngIf="app.app === activeChild">
                <li *ngFor="item in app.menu" nz-menu-item nzMatchRouter> 
                    <a [routerLink]="item.url">{{item.text}}</a>
                </li>
            </ul>
        </div>
    </li>