我有一个名为select.component的组件(选择器:'app-select'),它使用typeahead搜索用户(为了简单起见,我省略了这个选项)。然后,我希望通过绑定到ng-模板中的项来显示名称和employeeId。
<ng-select>
<ng-template ng-option-tmp let-item="item">
{{item.name}}</br>
{{item.employeeId}}
</ng-template
</ng-select>当我们在应用程序中使用这些ng选择元素时,我已经使select.component成为其他父组件使用的可重用组件。因此,我希望使ng模板部件动态化,并让它从父组件传入。我将select.component改为如下所示:
<ng-select>
<ng-template ng-option-tmp let-item="item">
<ng-content></ng-content>
</ng-template
</ng-select>然后我有了user.component,它使用内容投影在select.component中填充ng模板,如下所示:
<app-select>
{{item.name}}</br>
{{item.employeeId}}
</app-select>这里的问题是,当内容投影将app-select的内部html传递给ng-模板时,{{item.name}}和{item.employeeId}}没有在ng-模板中计算。在项的下拉列表中,我看到{{item.name}},而不是实际的名称值。
我如何才能最好地做到这一点?我确实需要父组件能够指定下拉项应该如何使select.component完全可重用。
见我的stackblitz
发布于 2018-06-21 15:12:35
您需要在组件中传递代码,在选择组件中捕获。
<app-select>
<ng-select [items]="items" bindLabel="name" placeholder="Works">
<ng-template ng-option-tmp let-item="item">
{{item.name}}<br/>
{{item.employeeId}}
</ng-template>
</ng-select>
</app-select>那你就需要用
<ng-content></ng-content>在选择组件中
这样你就能得到你想要的东西。
发布于 2019-06-14 21:09:02
我同意将公共设置封装在组件中是有帮助的,并允许组件的使用者提供其余的设置。
当父标记提供模板时,NgSelect使用@ContentChild()获取组件标记中提供的模板。我怀疑<ng-content>尚未可用,因为ngAfterContentInit生命周期挂钩是在ngAfterViewInit之前调用的。
另一种方法是在视图初始化后,接受TemplateRef作为<app-select>的输入,并手动设置NgSelect的optionTemplate:
export class SelectComponent implements AfterViewInit {
@Input() items: any[];
@Input() optionTemplate: TemplateRef<any>; // The options template to provide to ng-select
@ViewChild(NgSelectComponent) ngSelect: NgSelectComponent; // A reference to the ng-select component
// Once @ViewChild is defined after view init
ngAfterViewInit() {
if (this.optionTemplate) {
// Manually assign ng-select's optionTemplate from the input
this.ngSelect.optionTemplate = this.optionTemplate;
}
}
}然后您可以通过引用变量传递一个模板,您可以引用:
<app-select [items]="items" [optionTemplate]="appSelectOption">
</app-select>
<ng-template #appSelectOption let-item="item">
{{item.name}}<br/>
{{item.employeeId}}
</ng-template>这样,您可以将模板出口上下文(let-item="item")保留在使用变量的同一区域。
发布于 2018-06-21 15:22:53
在没有任何结构指令或模板参考变量的情况下,模板永远不会工作。您可以使用ng容器而不是ng模板。对不起,缺少任何东西,因为我已经用手机回答了这个问题。
https://stackoverflow.com/questions/50970593
复制相似问题