【问题标题】:Create TemplateRef in a Angular 10 service在 Angular 10 服务中创建 TemplateRef
【发布时间】:2021-01-13 15:55:55
【问题描述】:

我们在 Angular 10 项目中使用 ngZorro。现在我想打开抽屉 (https://ng.ant.design/components/drawer/en) 来显示表格。场景是一个列表,例如产品,然后单击其中一个产品,它的表单应在抽屉中打开。

我正在使用 NzDrawerService 创建抽屉,但我无法设置任何页脚(称为 nzFooter)。

例如,有一个 ProductFormComponent,所以在我的 ProductService.ts 中我可以调用:

openForm(){
  const drawerRef = this.drawerService.create({
      nzTitle: 'My Title',
      nzContent: ProductFormComponent
  });
  drawerRef.open()
}

现在,还有一个预定义页脚 (nzFooter?: string | TemplateRef<{}>) 的选项,我想在其中添加保存和取消按钮。 现在的问题是:如何在此处获取 TemplateRef,因为该函数是在服务中而不是在组件中调用的?

【问题讨论】:

  • 如何从调用服务中的函数的组件传递一个模板引用(所以不是openForm(),而是openForm(template: TemplateRef<any>)
  • 这正是我想要阻止的。否则,使用该服务(甚至通过其他服务)的每个组件都必须有一个模板。在 CRUD 服务中,保存和取消按钮的模板总是相同

标签: angular typescript ng-zorro-antd


【解决方案1】:

如果我想将一个模板注入到服务中,我会使用一个“虚拟”组件,我将使用它来将一个模板注入到我的服务中。

您可以在抽屉服务上添加一个函数来设置模板引用:

private tempalte: TemplateRef<any>;
setTemplate(template: TemplateRef<any>) {
  this.tempalte = template;
}

组件看起来像:

@Component({
  selector: "template-injector",
  template: `
    <ng-template #myTemplate>
      <h1>Best Template!</h1>
    </ng-template>
  `,
  styleUrls: []
})
export class TemplateInjectorComponent implements AfterViewInit {
  constructor(private derviceService: DrawerService) {}

  @ViewChild("myTemplate") template: TemplateRef<any>;

  ngAfterViewInit(): void {
    this.derviceService.setTemplate(this.template);
  }
}

最后,在你的应用程序中找到一个主要组件并加载 TemplateInjectorComponent,因为模板只是 &lt;ng-template&gt;,所以没有渲染任何内容(添加它的好地方是在布局组件的末尾)。

或者,您可以将其添加到主应用程序组件中,而不是创建新组件。

【讨论】:

  • 这可能是一个解决方案。一次只能有一个模板,我说得对吗?
  • 使用列出的解决方案,但您可以扩展它并使用许多模板(或数组或记录)创建一个对象,我只是想传达一般的想法,但是您还必须指定打开时的模板
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多