NgSwitch
容器上的 [ngSwitch]
指令指定要匹配的表达式。匹配的表达式由容器内视图上的 ngSwitchCase
指令提供。
The [ngSwitch]
directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase
directives on views within the container.
参见
Exported from
选择器
[ngSwitch]
属性
属性 | 说明 |
---|---|
@Input() | 只写 |
说明
如果有匹配项,则渲染匹配的视图。
Every view that matches is rendered.
如果没有匹配项,则渲染
ngSwitchDefault
If there are no matches, a view with the
ngSwitchDefault
directive is rendered.[NgSwitch]
语句内任何除NgSwitchCase
或ngSwitchDefault
指令之外的元素都保留在原位。Elements within the
[NgSwitch]
statement but outside of anyNgSwitchCase
orngSwitchDefault
directive are preserved at the location.
为指令定义一个容器元素,并指定要匹配的 switch 表达式作为属性:
Define a container element for the directive, and specify the switch expression to match against as an attribute:
<container-element [ngSwitch]="switch_expression">
在容器内, *ngSwitchCase
语句将匹配表达式指定为属性。包括用 *ngSwitchDefault
作为最后一种情况。
Within the container, *ngSwitchCase
statements specify the match expressions as attributes. Include *ngSwitchDefault
as the final case.
<container-element [ngSwitch]="switch_expression">
<some-element *ngSwitchCase="match_expression_1">...</some-element>
...
<some-element *ngSwitchDefault>...</some-element>
</container-element>
使用范例
Usage Examples
下面的示例演示如何使用多个分支来显示同一视图:
The following example shows how to use more than one case to display the same view:
<container-element [ngSwitch]="switch_expression">
<!-- the same view can be shown in more than one case -->
<some-element *ngSwitchCase="match_expression_1">...</some-element>
<some-element *ngSwitchCase="match_expression_2">...</some-element>
<some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
<!--default case when there are no matches -->
<some-element *ngSwitchDefault>...</some-element>
</container-element>
以下示例演示如何嵌套案例:
The following example shows how cases can be nested:
<container-element [ngSwitch]="switch_expression">
<some-element *ngSwitchCase="match_expression_1">...</some-element>
<some-element *ngSwitchCase="match_expression_2">...</some-element>
<some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
<ng-container *ngSwitchCase="match_expression_3">
<!-- use a ng-container to group multiple root nodes -->
<inner-element></inner-element>
<inner-other-element></inner-other-element>
</ng-container>
<some-element *ngSwitchDefault>...</some-element>
</container-element>