2017-08-15 57 views
1

標題可能會引起誤解,讓我詳細說明。將值傳遞給組件時,是否有可選的input()條件?

可以說我們有一個集合並使用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]

我該如何做到這一點?

回答

1

你可以只使用三元運算符來檢查,如果你是目前最後一個元素:

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

然後,你可以爲其他投入這樣做。

+0

這正是我的想法,但問題是'null'。如果它爲空,那麼未定義的錯誤將會吐出,使用它來獲取prevCard的屬性(如果它存在的話) – James

+0

那麼你需要檢查它是否爲null。就我所知,這樣的事情無法用角度來處理。 – Christian

+0

我想[prevCard]甚至不顯示在HTML中的DOM不是最後一個。可能嗎? – James

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的說法,沒有其他辦法。

0

好的,謝謝你們的幫助。我設法做你的建議來解決問題,但條件是有點不同:

<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如果條件不滿足,這是我想要的。

再次感謝您的幫助。

相關問題