首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在子组件中将ng内容传递给ng模板元素并不绑定到属性。

在子组件中将ng内容传递给ng模板元素并不绑定到属性。
EN

Stack Overflow用户
提问于 2018-06-21 14:08:17
回答 3查看 3.3K关注 0票数 2

我有一个名为select.component的组件(选择器:'app-select'),它使用typeahead搜索用户(为了简单起见,我省略了这个选项)。然后,我希望通过绑定到ng-模板中的项来显示名称和employeeId。

代码语言:javascript
运行
复制
<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改为如下所示:

代码语言:javascript
运行
复制
<ng-select>
  <ng-template ng-option-tmp let-item="item">
    <ng-content></ng-content>
  </ng-template
</ng-select>

然后我有了user.component,它使用内容投影在select.component中填充ng模板,如下所示:

代码语言:javascript
运行
复制
<app-select>
  {{item.name}}</br>
  {{item.employeeId}}
</app-select>

这里的问题是,当内容投影将app-select的内部html传递给ng-模板时,{{item.name}}和{item.employeeId}}没有在ng-模板中计算。在项的下拉列表中,我看到{{item.name}},而不是实际的名称值。

我如何才能最好地做到这一点?我确实需要父组件能够指定下拉项应该如何使select.component完全可重用。

见我的stackblitz

EN

回答 3

Stack Overflow用户

发布于 2018-06-21 15:12:35

您需要在组件中传递代码,在选择组件中捕获。

代码语言:javascript
运行
复制
<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>

那你就需要用

代码语言:javascript
运行
复制
<ng-content></ng-content>

在选择组件中

这样你就能得到你想要的东西。

票数 1
EN

Stack Overflow用户

发布于 2019-06-14 21:09:02

我同意将公共设置封装在组件中是有帮助的,并允许组件的使用者提供其余的设置。

当父标记提供模板时,NgSelect使用@ContentChild()获取组件标记中提供的模板。我怀疑<ng-content>尚未可用,因为ngAfterContentInit生命周期挂钩是在ngAfterViewInit之前调用的。

另一种方法是在视图初始化后,接受TemplateRef作为<app-select>的输入,并手动设置NgSelect的optionTemplate

代码语言:javascript
运行
复制
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;
    }
  }
}

然后您可以通过引用变量传递一个模板,您可以引用:

代码语言:javascript
运行
复制
<app-select [items]="items" [optionTemplate]="appSelectOption">
</app-select>

<ng-template #appSelectOption let-item="item">
  {{item.name}}<br/>
  {{item.employeeId}}
</ng-template>

这样,您可以将模板出口上下文(let-item="item")保留在使用变量的同一区域。

你的StackBlitz叉

票数 1
EN

Stack Overflow用户

发布于 2018-06-21 15:22:53

在没有任何结构指令或模板参考变量的情况下,模板永远不会工作。您可以使用ng容器而不是ng模板。对不起,缺少任何东西,因为我已经用手机回答了这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50970593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档