从组件传递ng-template到ng选择Inside Another Component

问题描述 投票:1回答:1

我正在尝试将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>

我正在努力实现与此类似的东西:

选择-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>
angular angular7 angular-ngselect
1个回答
0
投票

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

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

CustomChine.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'}
    ];

}

定制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>  
© www.soinside.com 2019 - 2024. All rights reserved.