【问题标题】:Is there such thing as optional input() condition when passing value to components?将值传递给组件时是否存在可选的 input() 条件?
【发布时间】:2017-08-15 09:23:18
【问题描述】:

标题可能会误导,让我详细说明。

假设我们有一个集合并使用ngfor 将它们绑定到 html 中。然后对于每个集合,根据条件我们将值传递给子组件。例如:

<ng-template ngFor let-person="$implicit" [ngForOf]="peopleAsPreviousCurrentAndNextTriplets" let-i=index let-last=last>
  <app-card 
  [decrement]="(2 - i)" 
  [defaultDiff]="(+30) * (2 - i)" 
  [prevCard]="person.previous" 
  [currentCard]="person.current" 
  [nextCard]="person.next"
  ></app-card>
</ng-template>

如您所见,我们将[prevCard][currentCard][nextCard] 传递给集合中每个元素的组件。

但是我不想要这个。

我只想在last 上通过[prevCard][currentCard][nextCard]。如果不是last,那么我只想通过[currentCard]

我该怎么做?

【问题讨论】:

    标签: angular typescript collections ngfor


    【解决方案1】:

    好的,谢谢大家的帮助。我按照您的建议设法解决了这个问题,但情况有点不同:

    <ng-template ngFor let-person="$implicit" [ngForOf]="peopleAsPreviousCurrentAndNextTriplets" let-i=index let-last=last>
      <app-card 
          [decrement]   = "(2 - i)" 
          [defaultDiff] = "(+30) * (2 - i)" 
          [prevCard]    = "last ? person.previous : null" 
          [currentCard] = "person.current" 
          [nextCard]    = "last ? person.next : null"
      ></app-card>
    </ng-template>

    如果条件失败,这基本上甚至不会在 html 中显示,这正是我想要的。

    再次感谢您的帮助。

    【讨论】:

      【解决方案2】:

      您可以只使用三元运算符来检查您当前是否在最后一个元素上:

      [prevCard]="last === person ? person.previous : null" 
      

      然后你可以对其他输入做同样的事情。

      【讨论】:

      • 这正是我的想法,但问题是null。如果它为空,那么会吐出一个未定义的错误, 使用它来获取 prevCard 的属性(如果存在)
      • 那么你必须检查它是否为空。据我所知,Angular 无法处理这样的事情。
      • 我想 [prevCard] 甚至不显示在 html 中的 DOM 中,这不是最后一个。有可能吗?
      • 这是不可能的。
      • 这对我有帮助。谢谢,我用的是角材质侧导航栏,[fixedInViewport]="fixedNavBar",其中fixedNavBar会根据条件取值'true'/'false',ts文件中的逻辑。
      【解决方案3】:
      <ng-template ngFor let-person="$implicit" [ngForOf]="peopleAsPreviousCurrentAndNextTriplets" let-i=index let-last=last>
        <ng-container *ngIf="person===last"> // or what ever else the condition could be
           <app-card 
            [prevCard]="person.previous" 
            [currentCard]="person.current" 
            [nextCard]="person.next">
           </app-card>
        </ng-container>
      
           <ng-container *ngIf="someOtherCondition"> // or what ever else the condition could be
                <app-card  // you get the idea ? 
                   [nextCard]="person.next"></app-card>
            </ng-container>
       </ng-template>
      

      你必须像上面那样处理你的情况,或者按照@Christian所说的,别无他法。

      【讨论】:

        猜你喜欢
        • 2018-05-01
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        相关资源
        最近更新 更多