在 Angular 10 服务中创建 TemplateRef

Create TemplateRef in a Angular 10 service

我们在 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,因为该函数是在服务中调用的,而不是在组件中调用的?

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

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

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,因为模板只是 <ng-template>,没有渲染任何内容(添加它的好地方是在布局组件的末尾).

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