将值传递给组件时是否有可选的input()条件?

时间:2017-08-15 09:23:19

标签: angular typescript collections ngfor

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

假设我们有一个集合,并使用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]传递给集合中每个元素的组件。

但我不想要这个。

我只想在[prevCard]时传递[currentCard][nextCard]last。如果不是last,那么我只想传递[currentCard]

我怎么能在这里这样做?

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

<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所说的那样,没有别的办法。

答案 2 :(得分:0)

好的谢谢你的帮助。我设法按照你的建议修复了这个问题,但条件有点不同:

&#13;
&#13;
app.directive("scrolledDown", function ($window) {
return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
        angular.element($window).off("scroll");
        angular.element($window).bind("scroll", function () {               
            if ($(window).scrollTop() + $(window).height() + 5 >= $(document).height()) {
                $(window).scrollTop($(window).scrollTop() - 10);
                scope.$parent.$apply(attrs.scrolledDown);                    
            }
        });
    }
}
});
&#13;
&#13;
&#13;

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

再次感谢您的帮助。