Guide: "Implementing a dynamic template reference in a function"

I have a function below that uses the setModelData method.

My question is about making the template variable dynamic for both the getGlobalList and getNonGlobalList functions.

For Example:

1) If getGlobalList is running, it will set template: this.CustomTableItemTemplate inside the setModelData function.

2) If getNonGlobalList is running, it will pass template: this.NonGlobalCustomTableItemTemplate inside the setModelData function.

Thank you for your assistance.

Code:

@ViewChild('CustomTableItemTemplate') CustomTableItemTemplate: TemplateRef<any>;
@ViewChild('NonGlobalCustomTableItemTemplate') NonGlobalCustomTableItemTemplate: TemplateRef<any>;


ngOnInit() {
  this.getGlobalList();
  this.getNonGlobalList();  
}

getGlobalList() {
  this.globalSchemamodel.data.length = 0;

  this.Service.getGlobalList(
    this.constructQueryParam(this.globalSchemamodel, 'global'))
      .subscribe((response: any) => {
        const globalSchemas = response ? response.data : [];
        if (globalSchemas.records) {
          this.setModelData(globalSchemas, this.globalSchemamodel);
        }     
      });
} 

getNonGlobalList() {
  this.nonGlobalSchemamodel.data.length = 0;

  this.Service.getList(
    this.constructQueryParam(this.nonGlobalSchemamodel, 'nonglobal'))
      .subscribe((response: any) => {
        const nonglobalschemaslist = response ? response.data : [];
        if (nonglobalschemaslist.records) {
          this.setModelData(nonglobalschemaslist, this.nonGlobalSchemamodel);
        }     
      });

} 

setModelData(globalSchemas, globalSchemamodel) {
  for (const schema of globalSchemas.records) {
    const tableModel = [
     new TableItem({ data: schema.schema_id }),
       this.isAdminRole ? new TableItem({
       data:[{ 'schemaId': schema.schema_id }],
       **template: this.CustomTableItemTemplate**
     }) : null
    ];
    globalSchemamodel.data.push(tableModel);
  }
}

Answer №1

The setModelData function definitely requires an additional template parameter.

Furthermore, you have the opportunity to refactor similar code from getNonGlobalList and getGlobalList

ngOnInit() {
  this.getList(
    this.globalSchemamodel,
    this.Service.getGlobalList,
    'global',
    this.CustomTableItemTemplate
  );
  this.getList(
    this.nonGlobalSchemamodel,
    this.Service.getList',
    'nonglobal',
    this.NonGlobalCustomTableItemTemplate
  );  
}

getList(model: any, functionToCall: any, paramName: string, template: TemplateRef<any>) {

  model.data.length = 0;

  functionToCall(
    this.constructQueryParam(model, paramName))
      .subscribe((response: any) => {
        const schemas = response ? response.data : [];
        if (schemas.records) {
          this.setModelData(schemas.records, model);
        }     
      });
} 

setModelData(schemas: any[], schemaModel: any, template: TemplateRef<any>) {
  for (const { schema_id } of schemas) {
    const tableModel = [
      new TableItem({ 
        data: schema_id
      }),
      this.isAdminRole ? new TableItem({
        data: [
          {
            'schemaId': schema_id
          }
         ],
         template
       }) : null
    ];
    schemaModel.data.push(tableModel);
  }
}

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

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Leveraging TypeScript Declarations for an External JavaScript Library

Struggling to find clear documentation on how to properly use the ALKMaps JavaScript library in my Ionic application. I created a local npm module with an alkmaps.d.ts file, but I can't seem to import it into my Angular code without encountering error ...

Steps to create a clickable image input

How can I make an image clickable in an input with type=file? <label for="formFileSm" class="label_display form-label">avatar</label> <input class="width_input mx-auto form-control form-control-sm" id="fo ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...

Infinite Scrolling with Angular Using a For Loop

The information I'm displaying pertains to the search query entered. Currently, all results are shown simultaneously. My goal is to display 6 pieces of data at a time and load the rest as the user scrolls down. <li *ngFor="let category of categor ...

Using Angular's RxJs: A BehaviorSubject can trigger an HTTP request, which in turn triggers the next value

i'm facing an issue with circular dependency. I attempted to use switchMap(() => EMPTY), take(1) approach to resolve it. While this solution works, it's not ideal. Here's a snippet of the code: P.S. ConstructorGeneratorService creates a ...

Determine a person's vertical measurement with jQuery

Is there a way to determine the distance from the top of the page to where a link has been inserted? For example, we can use the following code snippet to calculate the height of the window: w = $(window).height(); I am interested in finding out how to ...

Refresh ngFor when the Input value is modified

I am currently exploring Angular 2 to deepen my understanding. In this project, I am fetching a list of people from an API endpoint. However, the list is dynamic and changes periodically. Here's a snippet of my People Component: @Component({ selec ...

Exploring the Comparison Between Angular RxJS Observables: Using takeUntil and unsubscribing via Subscription

When it comes to unsubscribing from observables in Angular components utilizing ngOnDestroy, there are multiple approaches available. Which of the following options is more preferable and why? Option 1: takeUntil The usage of RxJS takeUntil for unsubscri ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

The Angular frontend appears to be experiencing difficulties displaying content on the website

I'm currently working through the AngularJS on Rails tutorial from Thinkster(). Check out my progress so far https://jsfiddle.net/dcbavw4e/ I'm not seeing anything on the web page. I've already installed node.js and npm. Are there any othe ...

Delaying the doubling up process

I have a situation with two divs containing start and stop buttons that act as timers. I am creating a JSON object to store time variables and other data. When I click on the start button, the timer functions properly. I assign the timeout function to one ...

Clear the history of a dynamically generated button using jQuery

Greetings fellow StackOverflow users! I'm currently tackling a project that requires jQuery to implement a master/detail table layout in asp.net C#. The master and detail tables need to be generated dynamically. The issue I'm facing involves gen ...

Issue: Map container not located when implementing a leaflet map with Angular

Here is the complete error message: core.js:6479 ERROR Error: Map container not found. at NewClass._initContainer (leaflet-src.js:4066) at NewClass.initialize (leaflet-src.js:3099) at new NewClass (leaflet-src.js:296) at Object.createMap [a ...

The MongoDB connection in NextJS 14 is causing a delay in loading the page

Occasionally, when trying to open a page through the dashboard menu, nothing happens on the frontend. There's no loading screen or any indication that the page is being loaded. How can this problem be prevented so that the page loads as intended? This ...

Phonegap not functioning properly with JQuery Ajax requests post compilation

After developing my project in node.js and using phonegap serve, I found that my AJAX functionality was working perfectly. However, upon creating an apk file for distribution testing, the AJAX call stopped functioning. Despite adding necessary configuratio ...

Repeatedly iterates through the JSON properties that have been grouped together

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF Upon examining a JSON object, the structure is as follows: var values = [ {"aname":"account1", "pname":"pname1", "vname":"vname1& ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Where exactly should you unsubscribe from Angular Observables?

I'm unsure about where to unsubscribe from an Observable. Here is the function in a component: loadProjectDetails(projectId: number): void { console.log('>> loadProjectDetails(), id=', projectId); const subscription = this.projec ...

Tips for maximizing performance in ember-data through r.js

After making the switch to ember-data#canary, I encountered a problem with r.js failing. [Error: Error: ENOENT, no such file or directory '/scripts/lib/ember-data/ember-data/core.js' In module tree: app/main app/app embe ...