I'd like to know what is the best way to avoid using multiple *ngIf in template. For example, in a component's template, depends on the route, i have to generate multiple different elements like that:
<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>
It'll become messy soon, so i came up with a solution, in this component's ts file, i defined an array:
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" }
]
In its template:
<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>
And i created a GeneratorComponent that receives the type and generate the corresponding element:
@Component({
selector: 'generator',
...
})
export class GeneratorComponent {
@Input() type: string;
@Input() content: string;
@Input() class: string;
@Input() menu_children: string;
}
GeneratorComponent's template:
<div *ngIf="type == 'text'"></div>
<i *ngIf="type == 'text'"></i>
...
The problem here is the class GeneratorComponent will have multiple properties and they are not used for one reason (for example: content and menu_children have no relation).
Do you have any idea to fix my solution ? Other solutions will be appreciated.
Thanks !
Aucun commentaire:
Enregistrer un commentaire