[英]Angular ngIf with multiple statements in else
如何在 else 下用多個語句編寫 ngIf? 我有一種感覺,我正在做一些愚蠢的事情,但很驚訝在這種情況下除了我之外沒有其他人。 *ngIf=col;='動作'; else showActions;iWouldLiketoAddAnotherAssignmentHere;
if(condition){
statement1;
statement2;
}else
{statement3;
statement4;
statement5;
}
只是有人不理解問題並不意味着問題不明確。這就是我上次離開SO的原因,停止標記您不理解的問題,讓其他理解的人回答或忽略它。
謝謝,我確實看過,但不符合我的要求。 我不認為我會被困在這么簡單的事情上,但我在這里。 當 if 條件評估為 true 或 false 時,我是否可以擁有多個語句?
我想你正在尋找ngSwitch
參考https://angular.io/api/common/NgSwitch
更新:
經過深思熟慮,我希望,我終於能夠弄清楚你在問什么......
<ng-container *ngIf="col !='actions'; else multilpleActions">
...
</ng-container>
<ng-template #multilpleActions>
<ng-container *ngTemplateOutlet="showAction"></ng-container>
<ng-container *ngTemplateOutlet="anotherAction"></ng-container>
</ng-template>
<ng-template #showAction>
...
</ng-template>
<ng-template #anotherAction>
...
</ng-template>
我真的希望這會有所幫助。
更新(編輯后)
讓我指出, *ngIf
不適用於按順序運行的代碼語句,但適用於只是文本的 HTML 模板。 *ngIf
對單個元素執行boolean操作,並允許您從 2 個模板中提取 select,其中一個模板將被渲染到其中。 在任何給定時間,您只能將一個模板呈現給一個元素。 所以你要求的是不可能的。 如果您需要為一個元素呈現多個模板,唯一的出路是將它們作為父元素的子元素並將父元素呈現給元素。
快樂編碼!
您是否有機會尋找then else
?
<ng-container *ngIf="col !='actions'; then noActions; else showActions;></ng-container>
<ng-template #noActions>
I have no actions
</ng-template>
<ng-template #showActions>
I have some actions
</ng-template>
你甚至可以用多個擴展它
<ng-container *ngIf="col !='actions'; then noActions; else (col === 'actions' && showActions) || (something === 3 && somethingElse)";></ng-container>
<ng-template #noActions>
I have no actions
</ng-template>
<ng-template #showActions>
I have some actions
</ng-template>
<ng-template #somethingElse>
I have some something else
</ng-template>
根據最佳實踐,模板上不應有更多邏輯。 因為它可能會導致難以跟蹤錯誤和未經測試的場景。
在您的組件中移動這些邏輯。 並創建多個標志,然后嘗試顯示/隱藏確切的段。
在模板中處理此類多個條件的最佳方法是使用 ngSwitch,查看 Angular 文檔https://angular.io/api/common/NgSwitch
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.