2

I want to crate a nested layer.

@Component({
    selector: 'items-collection',
    template: '<ng-content></ng-content>'
})
export class ItemsComponent {
}

HTML usage is like this:

<items-collection>
    <item [name]="item-1"></item>
    <item [name]="item-2"></item>
    <item [name]="item-3"></item>
</items-collection>

But if I set a json source data of items-collection the data will append dynamically.

@Component({
    selector: 'items-collection',
    template: '<ng-content></ng-content>'
})
export class ItemsComponent {
    private jsondata:any[] = [
        {"name": "item-8"}, 
        {"name": "item-9"},
        {"name": "item-15"}
    ]
}

<items-collection source="jsondata">
    <item [name]="item-1"></item>
    <item [name]="item-2"></item>
    <item [name]="item-3"></item>
</items-collection>

Is this possible?

1
  • 1
    Why is *ngFor not useful in this case? Commented Jun 12, 2019 at 8:07

2 Answers 2

1

In ItemsComponent,

@Component({
    selector: 'items-collection',
    template: `<ng-container *ngFor=let data of jsonData">
                  <item [name]="data.name"></item>
              </ng-container>`
})  
export class ItemsComponent {
    @Input('source') jsonData: any[] = [];
}

And where you want to include item-collection,

In that component ts and html file include this code,

private jsondata:any[] = [
        {"name": "item-8"}, 
        {"name": "item-9"},
        {"name": "item-15"}
    ]


<items-collection [source]="jsondata">       
</items-collection>
Sign up to request clarification or add additional context in comments.

Comments

0

You can combine <ng-content> with a normal *ngFor:

@Component({
    selector: 'items-collection',
    template: `
      <ng-content></ng-content>
      <item *ngFor="let item of source" [name]="item.name"></item>
    `
})
export class ItemsComponent {
  @Input() source?: { name: string }[];
}

Make sure to use input binding

<items-collection [source]="jsondata">
    <item [name]="'item-1'"></item>
    <item [name]="'item-2'"></item>
    <item [name]="'item-3'"></item>
</items-collection>

1 Comment

@khush if he wants some default items in the list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.