Click here to Skip to main content
15,845,213 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this application where several lists on diferent components are being made.
The pattern for the component is always the same.

Master list items with ADD button and a REMOVE button for each item.
But the item itself vary alot, and some have its own list items.

I was trying to create a shareable component (cause DRY huh? :D )

But I cant' get to my **ngFor** to repeat the items inside the component.

I made this Stackblitz with the work.

What I have tried:

Component usage:

<chained-item-list [items]="items" (onRemoveItem)="onRemoveItem($event)">
    <div class="card">
        <h4>Header Item</h4>
        <small>22/03/2022</small>
        <p>Lorem ipsum dolor amet.</p>
    </div>
</chained-item-list>



Component .html file

<div class="list-header">
    <h3>CHAINED LIST</h3>

    <button 
        (click)="addNewItem()" 
        type="button" 
        class="btn-add">Add New</button>
</div>

<ul>
    <ng-container *ngFor="let item of items; let indexItem = index">
        <li>
            <ng-content></ng-content>

            <button
                (click)="removeItem(indexItem)"
                type="button"
                class="btn-remove">X</button>
        </li>
    </ng-container>
</ul>


Component .ts file

export class ChainedItemListComponent {

    @Input() items: any[];
    @Output() onRemoveItem: EventEmitter<any> = new EventEmitter();


    constructor() {}

    addNewItem() {
        this.items.push(Math.floor(Math.floor(Math.random() * 100)));
    }

    removeItem(indexItem: number) {
        try {
            this.onRemoveItem.emit(this.items.splice(indexItem, 1)[0]);
        } catch (e) {
            this.onRemoveItem.emit(e);
            console.log(e);
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900