Generating a TemplateRef within an Angular 10 service

We are using ngZorro in our Angular 10 project. Currently, we want to implement a functionality where clicking on a product from a list will open its form in a drawer ().

To achieve this, we are utilizing NzDrawerService to create the drawer. However, we are facing challenges in setting up the footer (nzFooter).

For instance, let's consider a ProductFormComponent. In our ProductService.ts file, we have the following code snippet:

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

We also need to add buttons for save and cancel in the footer by specifying

nzFooter?: string | TemplateRef<{}>
. The issue arises when trying to incorporate a TemplateRef within a service function call rather than a component.

Answer №1

If I were to insert a single template into a service, one approach would be to use a "dummy" component specifically for this purpose.

To set a templateRef in the drawer service, you can add a function like this:

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

The dummy component might look something like this:

@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);
  }
}

Lastly, locate the main component in your application and load the TemplateInjectorComponent. Since the template is just <ng-template>, nothing will be displayed (consider placing it at the end of your layout component).

Alternatively, instead of creating a new component, you could incorporate it into the main app component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

Capacitor-powered Mobile App: Previewing Printer with Angular 16

Currently, I am working on mobile applications developed using Angular 16 and Capacitor. My goal is to display a print preview for the mobile application. The standard method with Windows.Print() function works fine for web and mobile web platforms, but i ...

Top Bootstrap Div with Sticky Scrolling Fixation

Trying to implement sticky-top from bootstrap to fix a div when scrolling. Implementing as follows: <div class="col-md-4"> <div class="sticky-top"> <app-reserva></app-reserva> </div> </div> Various sources sug ...

Issue with Angular environment file not being copied during ng serve or ng build operations

I need help with a seemingly simple problem that I'm stuck on. In my angular-cli.json file, I have various environment files set up as follows: "environmentSource": "environments/environment.ts", "environments": { "local": "environments/envir ...

material-icons appear differently when letter-spacing is applied in iOS browsers

To display levels using star icons from angular material, I wanted the stars to be shown next to each other. I attempted to achieve this by applying letter-spacing: -0.25rem;, but unfortunately it did not render correctly on iOS platforms (resulting in s ...

Is there a way to retrieve the anticipated DOM structure prior to the initialization of the view?

Consider this component: @Component({ selector: "form-control", template: ` <div class="form-group" #div> <label [for]="inputId">{{label}}</label> <ng-content></ng-content> <small [id]="helpId" cl ...

What could be causing the error message "SidebarDesktop has triggered a change in the order of Hooks detected by React"?

In my SideBarDesktop component, I define a constant called isSidebarSticky. This constant utilizes a custom hook named useStickyElement, which takes two arguments: const isSidebarSticky = styleStore.contentHeight ? useStickyElement(sideBarDomRef, style ...

Obtaining parameter types for functions from deeply nested types

I'm currently facing a challenge involving deeply nested parameters. When dealing with non-nested parameters, everything functions smoothly without any issues export type test = { 'fnc1': () => void, 'fnc2': () => void, ...

How is it possible for me to assign a literal containing unknown properties to a variable of type {}?

Upon running the code below, it fails type checking with an error message stating: Object literal may only specify known properties type A = {a: number} const a:A = {a:42, b: 43}; However, when the following code is executed, it succeeds: type A = {} ...

Utilizing Angular 7 to extract data from the initial column of an Excel spreadsheet and store it within an array

Currently, I am in the process of uploading an excel file that contains an ID column as its first column. My goal is to extract all the IDs and store them in an array for future data management purposes. To accomplish this task, I am utilizing the XLSX l ...

The React component appears to be stuck in an endless loop of requesting data

I developed an API endpoint that returns product titles when users search. Now, on the frontend, I am planning to make API calls to this endpoint as users type in the input field. Initially, I created a component using the class-based approach in React, wh ...

Utilizing conditional binding with ngModel in Angular 5

In my Angular 5 project, I am facing some issues. I have two models called Person and Employee where Employee inherits from Person and has its own attributes. In the HTML file of my component, I created a form with several input fields: <input type="te ...

Improved method for linking two enums with similar appearances

Currently, I use two enums as shown: enum Tab { Approved = "Approved", Pending = "Pending", Sold = "Sold", } enum ProductStatus { Approved = "Approved", Pending = "Pending", Sold = "Sold&q ...

Error message in Angular 9: "The 'pipe' property is not recognized on the 'void' type"

I recently created a function for streaming audio in Angular: private streamObservable(url) { new Observable(observer => { // Play audio this.audioObj.src = url; this.audioObj.load(); this.audioObj.play(); const handl ...

What is the process of determining if two tuples are equal in Typescript?

When comparing two tuples with equal values, it may be surprising to find that the result is false. Here's an example: ➜ algo-ts git:(master) ✗ ts-node > const expected: [number, number] = [4, 4]; undefined > const actual: [number, number] ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Having difficulty pushing code from the Vs Code interface to gitlab. Receiving error message "Git: [email protected]: Permission denied (publickey, keyboard-interactive)"

Being a Mac user, I've encountered an issue where my VS Code connection to GitLab seems incomplete. While I am able to commit code using the VS Code interface, I struggle with pushing the code to the repository directly from VS Code. Instead, I resort ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Exciting ngClass variation

I am facing a challenge of adding multiple classes to an element, with one of them being conditional. After referencing the documentation, I came across this method: <some-element [ngClass]="{'first': true, 'second': true, 'thi ...