angularangular7angular-ngselect

Pass ng-template From A Component To ng-select Inside Another Component


I'm trying to pass an ng-template from my main component into an ng-select inside another component. How can I do so?

I already tried to use ng-content or a template reference but it is still not working.

What I am trying to achieve is exactly the same as the ng-select custom template example, except that the ng-template is provided from another component. So instead of this:

<ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindValue="name">
    <ng-template ng-label-tmp let-item="item">
        <img height="15" width="15" [src]="item.avatar"/>
        {{item.name}}
    </ng-template>
</ng-select>

I'm trying to achieve something similar to this:

select-custom.component.html

<ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindValue="name">
    <ng-content></ng-content> --> This is not working, templateref is also not working
</ng-select>

app.component.html

<app-select-custom>
    <ng-template ng-label-tmp let-item="item">
        <img height="15" width="15" [src]="item.avatar"/>
        {{item.name}}
    </ng-template>
</app-select-custom>

Solution

  • To answer my own question. Thanks to @yurzui:

    stackblitz.com/edit/ng-select-43wmxu?file=app/app.component.ts

    ContentChild in custom-select.component.ts

    @Component({
      selector: 'app-custom-select',
      templateUrl: './custom-select.component.html',
      styleUrls: ['./custom-select.component.css']
    })
    export class CustomSelectComponent  {
       @ContentChild(TemplateRef) template: TemplateRef<any>
       cities = [
            {id: 1, name: 'Vilnius', avatar: 'https://avatars.io/platform/userId'},
            {id: 2, name: 'Kaunas', avatar: 'https://avatars.io/platform/userId'},
            {id: 3, name: 'Pavilnys', disabled: true, avatar: 'https://avatars.io/platform/userId'},
            {id: 4, name: 'Pabradė', avatar: 'https://avatars.io/platform/userId'},
            {id: 5, name: 'Klaipėda', avatar: 'https://avatars.io/platform/userId'}
        ];
    
    }
    

    custom-select.component.html

    <ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindValue="name">
      <ng-template ng-label-tmp let-item="item">
          <ng-template [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{item: item}"></ng-template>
      </ng-template>
    </ng-select>
    

    app.component.html

    <app-custom-select>
        <ng-template ng-label-tmp let-item="item">
            <img height="15" width="15" [src]="item.avatar"/>
            {{item.id}}
        </ng-template>
    </app-custom-select>