在 Angular 10 服务中创建 TemplateRef

Ind*_*von 4 typescript angular ng-zorro-antd

我们在 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()
}
Run Code Online (Sandbox Code Playgroud)

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

小智 7

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

您可以在抽屉服务上添加一个函数来设置 templateRef:

private template: TemplateRef<any>;
setTemplate(template: TemplateRef<any>) {
  this.template = template;
}
Run Code Online (Sandbox Code Playgroud)

该组件看起来像:

@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,找到应用程序中的主要组件并加载 TemplateInjectorComponent,因为模板只是<ng-template>,所以不会渲染任何内容(添加它的好地方是布局组件的末尾)。

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