Utilizing custom property within an extended MatPaginatorIntl class

I have been experimenting with some code and you can find it here: Test my Code on Stackblitz

To customize the labels of MatPaginator, I am using an extended MatPaginatorIntl class successfully. However, I want to introduce a custom variable (referred to as someProperty in this code snippet):

import { MatPaginatorIntl } from '@angular/material/paginator';
import { Injectable } from '@angular/core';

@Injectable()
export class CustomMatPaginatorIntl extends MatPaginatorIntl {
    public someProperty: number;
    constructor() {
        super();
        
        this.getAndInitTranslations();
    }
    
    setSomeProperty(value:number)
    {
        this.someProperty = value;
    }

    getAndInitTranslations() {

        this.itemsPerPageLabel = "Items per page";
        this.nextPageLabel = "Next";
        this.previousPageLabel = "Previous";
        this.changes.next();
    }
    override getRangeLabel = (page: number, pageSize: number, length: number) => {
        return `${this.someProperty}`; // use someProperty here
    }
}

In the paginator-configurable-example.ts file, I am trying to set that variable (e.g. in OnInit), but my current approach is not yielding results (apologies if it's totally off):

export class PaginatorConfigurableExample implements OnInit{
  @ViewChild(MatPaginatorIntl) pag: MatPaginatorIntl;
  // MatPaginator Inputs
  length = 100;
  pageSize = 10;
  pageSizeOptions: number[] = [5, 10, 25, 100];

  // MatPaginator Output
  pageEvent: PageEvent;

  setPageSizeOptions(setPageSizeOptionsInput: string) {
    this.pageSizeOptions = setPageSizeOptionsInput.split(',').map(str => +str);
  }
  ngOnInit(): void {
    // SET MatPaginatorIntl variable
    this.pag.setSomeProperty(100);
  }
}

How can I access the customized variable from the PaginatorConfigurableExample code?

Answer №1

@ViewChild is designed to work with classes that have the @Component / @Directive decorator applied. You can find more information in the Angular ViewChild Documentation

To solve this issue, follow these steps:

  1. Add the @Directive decorator to CustomMatPaginatorIntl instead of using @Injectable.
    @Directive({ selector: 'mat-paginator' })
    export class CustomMatPaginatorIntl extends MatPaginatorIntl {
        ...
    }
  1. In your main.ts file, remove CustomMatPaginatorIntl from the providers array and add it to the declarations array.
  declarations: [CustomMatPaginatorIntl, PaginatorConfigurableExample],
  1. In the
    paginator-configurable-example.ts
    file, update the type of ViewChild from MatPaginatorIntl to CustomMatPaginatorIntl
@ViewChild(CustomMatPaginatorIntl) pag: CustomMatPaginatorIntl;

You can see a working example by forking this code:https://stackblitz.com/edit/angular-vqbvpq-lj8xmi?file=app/paginator-configurable-example.ts

https://i.sstatic.net/IoIP8.png

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

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Having trouble with an external JavaScript file in Angular 5?

Recently, I decided to delve into the world of Angular and started my journey with angular5 by following this tutorial. Currently, I am in the process of converting a traditional HTML template into an Angular5 version but have encountered some challenges ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

Scroll automatically to the last div whenever a button is clicked using React and Typescript

I'm currently working on an application being developed in React + Typescript. I am trying to implement auto-scroll functionality to the last div within a parent div where child divs are dynamically added based on data from an array of objects. The da ...

Learn how to customize the global style within a child component in Angular and restrict the changes to only affect that specific component

I have applied some custom css styling in my global style.css file (src/style.css) for my Angular project. However, I encountered a problem when trying to override this styling in a specific component without affecting the rest of the project. Currently, I ...

The names of properties in Typescript are determined by the values of the outer type properties

In my project, I have various interfaces (or types) defined as follows: export type simpleValue = string | number | boolean | Date | null; export interface Options { inline?: OptionsItem[] | unknown[]; promptField?: string; selectedValues?: unknown[ ...

Exporting types with the `export =` syntax in TypeScript

For a code base that utilizes typescript export = syntax, I am looking to incorporate a new feature. The current code exports a function while also adding properties to it: const f = () => {}; f.someVal = 123; f.someFunc = () => {}; export = f; This ...

Invoke Observable.subscribe() sequentially

I have an array of objects and need to iterate over each element, making a request to the service for each one. However, I want to ensure that the next iteration only occurs when the current request is successfully completed, or block any further requests. ...

What kind of Typescript type should be assigned to setState when passed to the component?

In my setup, I have a variety of Parent components: const ParentOne = () => { const [error, setError] = useState<{ one: boolean }>({ one: false }); ...omit return ( <> <Child setErr={setError} name={"one"} /> </> ...

Increasing the value of a TypeScript variable using ngFor in an HTML template can enhance its usefulness

Can you dynamically increase a variable declared in your TypeScript file for each element generated by an ngFor loop in your HTML file? <tbody> <tr *ngFor="let item of invoiceItems"> <td>{{item.ItemName}}</td> <td>{ ...

I'm having trouble configuring the header in my Node/Express route

Using Node and the Express framework for my backend, along with React for my frontend, all coded in Typescript. The elastic search client is responsible for fetching data on the backend, but I don't believe that's where the issue lies. I'm ...

Troubleshooting the failure of chaining functions in Angular2 during an HTTP request

I want to organize functions based on their specific roles in the code Here's the situation: when I'm making an http request, I want to separate the function that handles attaching the access token and headers from the one responsible for actual ...

Executing the cucumberjs + playwright tests after starting the angular app using the ng serve command

Our testing process involves using cucumberjs and playwright. Is it possible to initiate Angular with ng serve (using test configuration) before running our tests, and then close the application once the tests are complete? Similar to configuring a web s ...

The property 'setParentKeyForNodeData' is not found in the 'Model' type. Perhaps you meant to use 'setCategoryForNodeData'?

As I work with gojs and utilize an organizational chart, I have encountered a problem with one of the context menus. Specifically, when selecting "Remove Role", I receive an error message stating Property 'setParentKeyForNodeData' does not exist ...

Error message when using an ionic search bar: "Encountered an issue with reading property srcElement, it

initializeItems() { this.items = this.productos; } getItems(searchbar) { this.initializeItems(); // setting 'q' to the value of the searchbar var q = searchbar.srcElement.value; // if the value is empty, do not filter ...

Having trouble with executing a "POST" operation in Spring framework?

After sending data from the angular service class, I included three parameters letter, documents, empList for the POST operation to the Api. export class LetterService { private baseUrl = 'http://localhost:8080/api/letter'; constructor(priv ...

Is there a way to create two slide toggles with unique colors on a single page?

How can I create two slide toggles with a unique color scheme on the same page? Looking to add some flair to your website with custom-colored slide toggles? Learn how to effortlessly incorporate two of them onto a single webpage here. ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

The data attribute in Cypress does not appear in the Angular Document Object Model

I've been attempting to integrate Cypress into my Angular project using data-cy attributes, but the behavior is quite inconsistent. Some areas display the attribute in the DOM, while others do not. For instance, in the following example, the data-cy ...