如何正确封装* ngFor原语中使用的一些显示逻辑?

时间:2018-04-13 13:51:45

标签: angular angular5 ngfor

我是角色5的新手,仍然试图从一些好的做法开始。我已经阅读过这个主题,但我找不到能帮助我做出选择的东西。

假设我们有这个要显示的基本项目列表。 href 属性取决于某些逻辑。

我在相关组件中编写了一个函数 isOK(),它将列表中的项目作为参数,并根据此项目的某些属性返回一个布尔值。

<ul>
    <li *ngFor="let item of itemList">
        <a [href]="isOK(item) ? aPath + item.name: '#'"  class="btn btn-default download-button"></a>
    </li>
</ul>

这样做有更好的方法吗?在这种情况下管道会更好吗?

1 个答案:

答案 0 :(得分:2)

我会使用像

这样的组件中的方法
getButtonLink(item: Type) {
    if(this.isOK(item)) {
        return `${aPath}/${item.name}`
    }

    return '#'
}

提高了可读性,也使测试更容易。

并像

一样使用它
<ul>
    <li *ngFor="let item of itemList">
        <a [href]="getButtonLink(item)"  class="btn btn-default download-button"></a>
    </li>
</ul>
相关问题