首页 > 解决方案 > Handle ul menu with angular 7

问题描述

I am working on angular 7 project and have ul list which is populated dynamically from server side.

I got the items no problem my problem is I need to close the ul item and reopen it after 4 li item.

How can I make that in angular using the next example?

<ul class="col-12 col-md-4 col-sm-6 list-unstyled">

  <li *ngFor="let footerPage of footerExtraPages; let i = index+1"><a routerLink="page/{{footerPage.id}}/{{footerPage.slug}}">{{footerPage.title}}</a></li>

</ul>

标签: angularangular7

解决方案


我想有几种方法可以解决它

一种是编写一个 getter 来获取元素:

html

  <li *ngFor="let footerPage of getFirstFour()">
    <a routerLink="page/{{footerPage.id}}/{{footerPage.slug}}"> 
      {{footerPage.title}}
    </a>
  </li>

ts

public function getFirstFour() {
  return this.footerExtraPages.map((item, i) => {
    if (i <= 4) { 
      return item;
    }
  })
}

然后创建一个新ul的,相应地得到其余的

为了避免不得不依赖模板 ( let i = index+1) 中的索引,您也可以使用一个函数来使索引保持一致:

public function getFirstFour() {
  return this.footerExtraPages.map((item, i) => {
    if (i <= 4) { 
      return { index: index + 1, ...item};
    }
  })
}

public function getRest() {
  return this.footerExtraPages.map((item, i) => {
    if (i > 4) { 
      return { index: index + 1, ...item};
    }
  })
}

请注意,如果 item 对象附加了一个 id,上面的代码可能会导致错误,如果您删除扩展运算符,您将能够保留两者,但也意味着您必须重新建模模板以更深层次.


推荐阅读