Budi
Budi

Reputation: 688

Extend ng-content Transclusion

I want to make a ng-content template for a component. But I cant find a tutorial how to solve this.

I want that the syntax in my views look like this:

<slider>
    <img src="url" alt="alt">
    <img src="url" alt="alt">
</slider>

My Slider Component:

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

@Component({
    selector: 'flx-slider',
    template: `
        <section class="slider">
            <div class="slider-inner">

                <ul>
                    <li>
                        <ng-content select="img"></ng-content>
                    </li>
                </ul>

            </div>
        </section>
    `,
    styleUrls: ['./module.flx-slider.component.scss'],
    encapsulation: ViewEncapsulation.None
})

export class FlxSliderComponent {

    constructor() {

    }

}

I think all see the problem. At last it must be so, that it creates for every img an extra li around the img. Anyone can tell me, how I can do this?

Upvotes: 2

Views: 1059

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657278

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

You can use <template> with <template [ngTemplateOutlet]="...">

<slider [data]="['url1', 'url2']">
  <template let-data><img [src]="data" alt="alt"></template>
</slider>
import {Component, ViewEncapsulation} from '@angular/core';

@Component({
    selector: 'flx-slider',
    template: `
        <section class="slider">
          <div class="slider-inner">
            <ul>
              <li *ngFor="let item of data">
                <template [ngTemplateOutlet]="templateRef" [ngOutletContext]="{$implicit: item}"></template>
              </li>
            </ul>
          </div>
        </section>
    `,
    styleUrls: ['./module.flx-slider.component.scss'],
    encapsulation: ViewEncapsulation.None
})

export class FlxSliderComponent {
    @ContentChild(TemplateRef) templateRef:TemplateRef;
    @Input()
    data:<any>[];
}

not tested

See also

Upvotes: 1

dovidweisz
dovidweisz

Reputation: 1234

You should use two components. One to iterate through the images, and one to use as a slider.

your final implementation code should look something like this:

<slider>
    <image-list [data]="['url1', 'url2']"></image-list>
</slider>

Slider Template:

<section class="slider">
    <div class="slider-inner">
        <ng-content></ng-content>
    </div>
</section>

List template:

<ul>
    <li *ngFor="let item of data">
        <img [src]="item.url">
    </li>
</ul>

Upvotes: 0

Related Questions