Yon*_*ree 7 angular2-template angular
我正在编写一些Angular2模板,这些模板具有不同容器的重复部分.在这种情况下,如果事物已分组并且启用了多节模式,则视图可能会更改.请原谅长长的例子,但是这样的话:
<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>
Run Code Online (Sandbox Code Playgroud)
我真的想重用部分内容而不必编写完全独立的组件并将它们连接在一起,这需要一个TypeScript文件和一个模板.一种方法是使用本地组件,如下所示:
<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" />
Run Code Online (Sandbox Code Playgroud)
我意识到上面是粗略的草图,可能不会按原样运行,但显然无法像这样重用部分视图是不幸的.如果我理解正确的话,React中的这种事情很简单.
我很好奇其他人已经解决了视图部分重用的优雅方式,而没有编写一个新的组件(我们的设计师需要了解它们和样式等等).谢谢.
如果您的部分结构相同,只是数据不同,您可以提出一个更通用的模型。不要直接引用它们category,而是thing将它们映射到您在服务到达视图之前填充到服务中的通用对象。
<div *ngFor="#item of items">
---
</div>
Run Code Online (Sandbox Code Playgroud)
这里的项目可以从事物或类别中填充。
然后你可以这样称呼它
<component [items]="fromThings"></component>
<component [items]="fromCategories"></component>
Run Code Online (Sandbox Code Playgroud)
您基本上是通过不直接依赖于实际对象来标准化视图。