我是 Angular 8 的新手。我使用的是 Angular 8。任何帮助或提示将不胜感激!
我试图实现以下伪代码:
if (condition1)
{
print1
}
else if (condition2)
{
print2
}
else
{
print3
}
Run Code Online (Sandbox Code Playgroud)
这是我只能实现的代码 if else
<ng-container *ngIf="(5>1);then resultOutOfRange else resultNA;">
</ng-container>
<ng-template #resultOutOfRange>
<td class="help-block">Result out of Range </td>
</ng-template>
<ng-template #resultNA>
<td>Result N/A</td>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
您正在寻找一个if/else块,然后寻找另一个if/else嵌套的块。没有办法像 javascript 那样堆叠它们,除非你有一个原子值,在这种情况下你可以使用ngSwitch类似于 switch/case 语句。
<ng-container *ngIf="CONDITION1; else resultNA;">
<p>Condition 1 is true</p>
</ng-container>
<ng-template #resultNA>
<ng-container *ngIf="CONDITION 2; else otherBlock;">
<p>Condition 2 is true</p>
</ng-container>
<ng-template #otherBlock>
<p>No conditions are true</p>
</ng-template>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
“我不能使用ngswitch,因为我的条件实际上很复杂。”...
在这种情况下,我建议您利用拥有组件代码(打字稿)的事实。在那里编写您的逻辑,然后在 HTML 模板中使用它,这将使您的代码更易于维护且更易于阅读。
示例请记住,您不必在 OnInit 中执行此操作,它也可以是调用的方法或随值更改而更改的其他内容)。
组件.ts
displayValue: number;
ngOnInit() {
displayValue = /*your logic here that dictates what it should be*/.
}
Run Code Online (Sandbox Code Playgroud)
.html
<container-element [ngSwitch]="displayValue">
<some-element *ngSwitchCase="1">...</some-element>
<some-element *ngSwitchCase="2">...</some-element>
<some-element *ngSwitchCase="3">...</some-element>
<some-element *ngSwitchDefault>...</some-element>
</container-element>
Run Code Online (Sandbox Code Playgroud)
另请参阅https://angular.io/api/common/NgIf和https://angular.io/api/common/NgSwitch
选项 1:嵌套 ngIf:
<ng-container *ngIf="condition1; then true1 else block2"></ng-container>
<ng-template #true1>true1</ng-template>
<ng-template #block2>
<ng-container *ngIf="condition2; then true2 else true3"></ng-container>
<ng-template #true2>true2</ng-template>
<ng-template #true3>true3</ng-template>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
或者,如果可能,使用 ngSwitch:
<div [ngSwitch]="switchCondition">
<ng-container *ngSwitchCase="case1">true1</ng-container>
<ng-container *ngSwitchCase="case2">true2</ng-container>
<ng-container *ngSwitchCase="case3">true3</ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)
ngSwitch 在您需要根据某个值进行切换的情况下工作,您可以使用您的代码根据任何条件的结果设置一些变量,通过switchCondition在 else if 块中赋值,例如:
if (condition1) {
this.switchCondition = 'case1'
} else if (condition2) {
this.switchCondition = 'case2'
} else {
this.switchCondition = 'case3'
}
Run Code Online (Sandbox Code Playgroud)
把它放在某个函数中并在适当的时候调用。
| 归档时间: |
|
| 查看次数: |
5234 次 |
| 最近记录: |