【问题标题】:Show only the first x li's without using ngFor in Angular 2在 Angular 2 中不使用 ngFor 只显示第一个 x li
【发布时间】:2017-05-27 12:29:43
【问题描述】:

我的模板中有 9 个<li> 元素,每个元素都有一个 *ngIf 条件。

其中 5 个可能返回 true 或更多或更少,但如果是这种情况,我只想显示前 4 个或更少。

<li>的顺序优先

我试过了:

// Template
<li *ngIf="checkCond(profile.Projects.length != 0)">Example</li>
... and so on...

// Component
shown: number = 0;

public checkCond(value: boolean): boolean {
    if (value) {
        this.shown += 1;
        return this.shown <= 4;
    }
    else return false;
}

我的方法的问题是if (value) 会持续触发,并且会像我预期的那样增加超过 9,因此最终它只会返回 false;

我不想使用 *ngFor

【问题讨论】:

  • “我不想使用 *ngFor”..为什么?
  • @PetrAdam 逻辑不允许我,我有覆盖、翻译和其他东西
  • 如果我理解您的问题,您需要显示不超过 4 个元素,但可能不是全部 4 个,同时您需要确定该元素是否可见?
  • @mautrok 完全正确 :)
  • 您还可以创建一个自定义管道,将数组限制为 4 个项目

标签: javascript angular typescript


【解决方案1】:

每次更改检测运行时都会调用checkCond()

而是将结果赋值给一个属性并绑定到该属性

constructor() { // or somewhere else
  this.checkCond(profile.Projects.length != 0);
}

cond:boolean;

public checkCond(value: boolean): boolean {
    if (value) {
        this.shown += 1;
        this.cond this.shown <= 4;
    }
    else this.cond = false;
}
<li *ngIf="cond">Example</li>

【讨论】:

  • 但是checkCond每次都会设置“cond”,你的意思是我应该为每个li创建一个checkCond?
  • 我不明白你的意思。当value 发生变化时,只需调用checkCond。这会更新 cond 并且 Angular 会更新您的视图(但仅在必要时更新 - 不是在每个更改检测周期。
  • 什么都不显示,其他的条件呢
  • 你想到的条件是什么?
  • checkCond 分配给我的答案。我刚刚在答案中明确添加了该字段。
  • 我看不出这是如何工作的,所以我得到了类似this.checkCond(this.profile.Projects.length != 0); this.checkCond(this.profile.Schools.length != 0); this.checkCond(this.profile.Study.length != 0); this.checkCond(this.profile.Websites.length != 0); this.checkCond(this.profile.Languages.length != 0); this.checkCond(this.profile.Hobby.length != 0); 的内容,而 li 将是:&lt;li *ngIf="cond"&gt;Projects&lt;/li&gt; &lt;li *ngIf="cond"&gt;Companies&lt;/li&gt; &lt;li *ngIf="cond"&gt;Schools&lt;/li&gt; ...
  • 【解决方案2】:

    如果你想使用这种类型的硬编码,我认为你应该在你的组件中创建一个数组和迭代器,f.e.

    someArray: boolean[] = [true, true, true, false, false, false];
    someIterator: number = 0;
    

    在您的 HTML 代码中:

    ...<li *ngIf="someArray[someIterator]">Example 1</li>
    {{someIterator = someIterator + 1}}
    <li *ngIf="someArray[someIterator]">Example 2</li>
    {{someIterator = someIterator + 1}}...
    

    但它的解决方案非常肮脏。对于这种情况,有 NgFor。

    我最后的想法是使用@ViewChildren 或@ContentChildren。你在尝试吗?

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签