简体   繁体   中英

Angular wrapper component iterating over children

I am trying to create a wrapper component in Angular, where the component can receive any number of children, and then wrap each item one by one. Preferably completely dynamically without binding any extra data.

The app-wrapper.component should work like this (only handles the logic for the wrapper) :

<div class="wrapper">
   <div 
      class="child-wrapper"
      *ngFor="let child of children"
   >
      <ng-content [select]="child"></ng-content>
   </div>
</div>

And using the app-wrapper (where the logic is handled for the items) :

<app-wrapper>
   <app-first-item></app-first-item>
   <app-second-item></app-second-item>
   ...
   <app-last-item></app-last-item>
</app-wrapper>

The app-wrapper.component is not working like this, throws an error:

Error: Template parse errors: Can't bind to 'select' since it isn't a known property of 'ng-content'.

Please note: The div.wrapper and the div.child-wrapper can't be separated.

it seems there are several possibilities to do this.

1/ You can make them into components:

app-wrapper.component:

<div class="wrapper">
  <div 
    class="child-wrapper"
    *ngFor="let child of children"
   >
    <app-item [item]="child"></app-item>
  </div>
</div>

and create ItemComponent with @Input to display an item.

2/ You can create a template reference with ngTemplateOutlet directive app-wrapper.component:

<div class="wrapper">
   <div 
      class="child-wrapper"
      *ngFor="let child of children"
   >
    <ng-container *ngTemplateOutlet="test; context: { child: child }"></ng-container>
   </div>
</div>

<ng-template #test let-child="child">
<!-- here an item -->
</ng-template>

ng-content is used to inject content inside an element as follows:

in your app-wrapper:

<div class="wrapper">
      <ng-content select="[child]"></ng-content>
</div>

and when you call your component:

  <app-wrapper>
    <div child>element you want to put inside the "ng-content" </div>
 </app-wrapper>

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