2

I have a component, <DropDown></DropDown> and I want to let the user pass in a template for the list items in the DropDown.

Assuming they want to make a custom list item that has an image and text they would do something like this:

<DropDown [data]="myData">
    <template>
        <span> <img src="..."> Some Text <span>
    </template>
</DropDown>

Inside the HTML of my DropDown component I have:

<div>
    <ul>
        <DropDownList [data]="data">
        </DropDownList>
    </ul>
</div>

In the DropDownList component I have the following HTML:

<li *ngFor="let item of data
    (click)="handleOnSelect(item)">
    [class.selected]="selectedItems.includes(item)">

    <template [ngWrapper]="itemWrapper>
    </template>
</li>

(I am using the template wrapper method from this post: Binding events when using a ngForTemplate in Angular 2)

This method works if I have the li elements within the DropDown component's HTML. However, I want to have wrap the li's into a DropDownList component and pass the template the user gave from DropDown into DropDownList.

Is it possible to do this?

Community
  • 1
  • 1
Sunny
  • 155
  • 1
  • 3
  • 9
  • I think that this is what you are after: https://toddmotto.com/transclusion-in-angular-2-with-ng-content . the ng-content tag. – Avi Sep 18 '16 at 19:25
  • Could you post more code? Do you use ngFor? – yurzui Sep 18 '16 at 19:45
  • I updated the code, I am using ngFor in the li to go through the data. @Avi I can't use ng-content because it doesn't work in ngFor loops. The ng-content will only be displayed once, not for every li element. Thats why I have to use the template method – Sunny Sep 18 '16 at 20:00

1 Answers1

4

You could try the following solution:

@Component({
  selector: 'DropDownList',
  template: `
   <li *ngFor="let item of items" (click)="handleOnSelect(item)">
    <template [ngTemplateOutlet]="itemWrapper" [ngOutletContext]="{ $implicit: item }">
    </template>
   </li>`
})
export class DropDownListComponent {
  @Input() itemWrapper: TemplateRef<any>;
  @Input() items: any;
  handleOnSelect(item) {
   console.log('clicked');
  }
}

@Component({
  selector: 'DropDown',
  template: `
    <div>
      <ul>
          <DropDownList [items]="items" [itemWrapper]="itemWrapper">
          </DropDownList>
      </ul>
    </div>`
})
export class DropDownComponent {
  @Input() items: string[];
  @ContentChild(TemplateRef) itemWrapper: TemplateRef<any>;
} 

@Component({
  selector: 'my-app',
  template: `
     <DropDown [items]="items">
       <template let-item>
            <h1>item: {{item}}</h1>
       </template>
    </DropDown>
  `
})
export class App { 
   items = ['this','is','a','test'];
}

Plunker Example

The ngTemplateOutlet(^2.0.0-rc.2) directive has the same functionality as your custom directive NgWrapper

See also related questions:

Community
  • 1
  • 1
yurzui
  • 205,937
  • 32
  • 433
  • 399