angular 模板可以可变吗?
Can angular templates be variable?
我在我的组件中声明了一个变量,我们将其命名为 "myVar"。根据这个变量,我想显示某个 ng-template。这是一个示例组件模板:
<div *ngIf="myVar; then myVar; else nothing"></div>
<ng-template #foo>My Foo-Content</ng-template>
<ng-template #nothing>No Content</ng-template>
有没有可能使这项工作?我希望 "myVar" 为空或名称 "foo",但上面的代码当然不会计算 "myVar"。
或者有什么办法解决这个问题?在我的实际应用程序中,"myVar" 有大约 10 个不同的值,但内容不足以使其成为自己的组件。
我必须为此制作 10 个不同的 *ngIf 吗? :(
NgSwitch 似乎是您要找的东西。
<div [ngSwitch]="myVar">
<div *ngSwitchCase="'Foo'">
Content
</div>
<div *ngSwitchCase="'Bar'">
Content
</div>
<div *ngSwitchDefault>
Empty or fallback
</div>
</div>
我在我的组件中声明了一个变量,我们将其命名为 "myVar"。根据这个变量,我想显示某个 ng-template。这是一个示例组件模板:
<div *ngIf="myVar; then myVar; else nothing"></div>
<ng-template #foo>My Foo-Content</ng-template>
<ng-template #nothing>No Content</ng-template>
有没有可能使这项工作?我希望 "myVar" 为空或名称 "foo",但上面的代码当然不会计算 "myVar"。
或者有什么办法解决这个问题?在我的实际应用程序中,"myVar" 有大约 10 个不同的值,但内容不足以使其成为自己的组件。
我必须为此制作 10 个不同的 *ngIf 吗? :(
NgSwitch 似乎是您要找的东西。
<div [ngSwitch]="myVar">
<div *ngSwitchCase="'Foo'">
Content
</div>
<div *ngSwitchCase="'Bar'">
Content
</div>
<div *ngSwitchDefault>
Empty or fallback
</div>
</div>