简体   繁体   中英

Creating a generic list iterator in Angular 2

I want to wrap a list of items, but I want the flexibility of supplying a unique template.

<list [items]="someItems">
    <book-list-item><!-- Books, cars, dogs, whatever -->
    </book-list-item><!-- This will contain a unique template -->
</list>

ListItemComponent

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

@Component({
    selector: 'list-item',
    template: `
        <div *ngFor="let item of items">
            <ng-content></ng-content><!-- Whatever book-list-item contains -->
        </div>`
})
export class ListItemComponent {
    @Input() items: Array<any>;
}

BookListItemComponent

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

@Component({
    selector: 'book-list-item',
    template: `
        <div class="row">
            <div class="col-xs-6">Books</div>
            <div class="col-xs-6">Rule</div>
        </div>`

})
export class BookListItemComponent {}

Obviously I'd be passing books as items , but this is just an example. I can get something similar to this working, but "Books Rule" only prints out in the last list-group-item (because Bootstrap).

I'm really looking to understand how to pass a generic component to parent component that will iterate over the generic component as an item in a list of items. Can someone point me in the right direction?

Take a look at this article . It does something very similar to what you need. Your main challange will be binding the values. You can also Look at Ben Nadel's article . It relates to RC1 and even he in the comments mentions that the setLocal is not there anymore and that you need to pass the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM