I am writing several Angular2 templates that have duplicate parts with different containers. In this case, the presentation may change if everything is grouped, and if the multi-section mode is enabled. Sorry for the long example, but something like this:
<template [ngIf]="isCategoryGrouped"> <div *ngFor="#categories of categories"> <div>{{ categories.category.name }}</div> <div *ngFor="#thing of categories.things"> <label *ngIf="isMultiSelectMode"> <input type="checkbox" (change)="updateThingSelection(thing, $event)" /> <img [src]="thing.image" /> {{ thing.name }} </label> <a href="javascript: void(0)" (click)="selectThing(thing)" *ngIf="! isMultiSelectMode"> <img [src]="thing.image" /> {{ thing.name }} </a> </div> </div> </template> <template [ngIf]="! isCategoryGrouped"> <div *ngFor="#thing of things"> <label *ngIf="isMultiSelectMode"> <input type="checkbox" (change)="updateThingSelection(thing, $event)" /> <img [src]="thing.image" /> {{ thing.name }} </label> <a href="javascript: void(0)" (click)="selectThing(thing)" *ngIf="! isMultiSelectMode"> <img [src]="thing.image" /> {{ thing.name }} </a> </div> </template>
I would really like to reuse parts of this without creating a completely separate component and putting it all together, which would require a TypeScript file and template. One method will be with local components, something like this:
<sub-component selector="thing-list" things="input"> <div *ngFor="#thing of things"> <label *ngIf="isMultiSelectMode"> <input type="checkbox" (change)="updateThingSelection(thing, $event)"/> <img [src]="thing.image" /> {{ thing.name }} </label> <a href="javascript: void(0)" (click)="selectThing(thing)" *ngIf="! isMultiSelectMode"> <img [src]="thing.image" /> {{ thing.name }} </a> </div> </sub-component> <template [ngIf]="isCategoryGrouped"> <div *ngFor="#categories of categories"> <div>{{ categories.category.name }}</div> <thing-list things="categories.things" /> </div> </template> <thing-list [ngIf]="! isCategoryGrouped" things="things" />
I understand that the above is a rough sketch and probably won't work as it is, but the apparent inability to reuse parts of the kind like this is unsuccessful. This question is pretty simple in React, if I understand correctly.
I’m curious how other people decided to reuse parts without thinking about writing a new component (which our designers then need to know and style, etc.).). Thanks.
source share