Angular2 local components / template reuse

大兔子大兔子 提交于 2019-12-05 05:48:58

If your sections are identical in structure, just different in data, you could come up with a more generic model. Instead of referring to category and thing directly, map them into a generic object that you populate in a service before it gets to the view.

<div *ngFor="#item of items">
        ---
</div>

Here items would either be populated from things or categories.

You can then call it like so

<component [items]="fromThings"></component>
<component [items]="fromCategories"></component>

You are basically normalizing the view by not depending on the actual objects directly.

You can also use *ngFor with [ngForTemplate] or the upcoming NgInsert (name will be changed) to make parts of your template reusable.

You can now use <ng-template>

<ng-template #headerPanel>
    <header>
       This is my reusable header.
    </header>
</ng-template>

Then use like this:

  <ng-container *ngTemplateOutlet="headerPanel"></ng-container>

Official docs

Note: I'm not knowledgeable enough to explain difference between [ngTemplateOutlet] and *ngTemplateOutlet but if someone else wants to edit this answer or add another feel free.

Call component recursively in template.

isList control which part to be used, default false.

thing.html

<template [ngIf]="isLlist">
    <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>

<template [ngIf]="!isList">

    <template [ngIf]="isCategoryGrouped">
        <div *ngFor="#categories of categories">
            <div>{{ categories.category.name }}</div>
            <my-thing-component [isList]="true" [things]="categories.things"></my-thing-component>
        </div>
    </template>

    <templete [ngIf]="! isCategoryGrouped">
        <my-thing-component [isList]="true" [things]="things"></my-thing-component>
    </templete>

</template>

thing.component.ts

import {Component,Input} from '@angular/core';

@Component({
    selector: 'my-thing-component',
    templateUrl: 'thing.html' 
})
export class ThingComponent {
    @Input() isList = false;
    @Input() things;

    //Fill in the rest
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!