【发布时间】:2023-04-11 00:43:01
【问题描述】:
我想知道避免在模板中使用多个 *ngIf 的最佳方法是什么。例如,在组件的模板中,取决于路由,我必须生成多个不同的元素:
<div *ngIf="route == 'page1'">Title for page 1</div>
<div *ngIf="route == 'page2'">Title for page 2</div>
<i *ngIf="route == 'page1'" class="fa fa-message"></i>
<i *ngIf="route == 'page2'" class="fa fa-bell-o"></i>
<div *ngIf="route == 'page1'">
<button>...</button>
</div>
<div *ngIf="route == 'page2'">
<div class="menu"></div>
</div>
很快就会变得乱七八糟,所以我想出了一个解决方案,在这个组件的 ts 文件中,我定义了一个数组:
arr_1 = [
{ type: "text", content: "Title for page 1" },
{ type: "icon", class: "fa fa-message" },
{ type: "button", content: "..." }
]
arr_2 = [
{ type: "text", content: "Title for page 2" },
{ type: "icon", class: "fa fa-bell-o" },
{ type: "menu", menu_children: [...], class: "menu" }
]
在其模板中:
<div *ngIf="route == 'page1'">
<generator *ngFor="let ele of arr_1"
[type]="ele.type"
[class]="ele.class"
[content]="ele.content"
[menu_children]="ele.menu_children"
>
</generator>
</div>
<div *ngIf="route == 'page2'">
<generator *ngFor="let ele of arr_2"
[type]="ele.type"
[class]="ele.class"
[content]="ele.content"
[menu_children]="ele.menu_children"
>
</generator>
</div>
并且我创建了一个GeneratorComponent,它接收类型并生成相应的元素:
@Component({
selector: 'generator',
...
})
export class GeneratorComponent {
@Input() type: string;
@Input() content: string;
@Input() class: string;
@Input() menu_children: string;
}
GeneratorComponent 的模板:
<div *ngIf="type == 'text'">{{ content }}</div>
<i *ngIf="type == 'text'">{{ content }}</i>
...
这里的问题是类 GeneratorComponent 将有多个属性,并且它们没有被使用的原因有一个(例如:内容和 menu_children 没有关系)。
您有任何想法来解决我的解决方案吗?其他解决方案将不胜感激。
谢谢!
【问题讨论】:
-
ngSwitch 也许?
-
GeneratorComponent没有问题
标签: templates angular design-patterns generator angular-ng-if