从一个组件传递ng-template到另一个组件内部ng-select

时间:2019-03-23 17:54:58

标签: angular angular7 angular-ngselect

我正在尝试将ng-template从我的主要组件传递到另一个组件内的ng-select中。我该怎么办?

已经尝试使用ng-content或模板引用,但仍无法正常工作。

我要实现的目标与ng-select自定义模板示例完全相同,只是ng-template是从另一个组件提供的。所以这很有趣:

<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>

我正在尝试达到以下目标:

select-custom.component.html

<ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindValue="name">
    <ng-content></ng-content> --> this is not working, templateref 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>

1 个答案:

答案 0 :(得分:0)

回答我自己的问题。感谢@yurzui:

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

custom-select.component.ts中的ContentChild

@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>