Is there a way to access the value of a public variable within the @input decorator of a function type?

I am working on a dropdown component that utilizes the @Input decorator to define a function with arguments, returning a boolean value.

dropdown-abstract.component.ts

    @Input() public itemDisabled: (itemArgs: { dataItem: any; index: number }) => boolean = () => false;

license-add.component.html

        <hf-shared-dropdown-small class="license-card__row-input"
                                  [id]="'expiryDate'"
                                  [required]="false"
                                  [itemDisabled]="itemDisabled"
                                  [isConfirmable]="false"
                                  [data]="expiryDates"
                                  [value]="selectedExpiryDate"
                                  (valueChange)="dateSelect($event)">
        </hf-shared-dropdown-small>

license-add.component.ts

    public getCustomer(): void {
        this.loading = true;
        this.customerService.getCustomer(this.customerId)
            .pipe(first(), finalize(() => this.loading = false))
            .subscribe((response: CustomerResponse) => {
                if (response && response.success) {
                   
                    this.customerName = response.name;
                    this.registeredTo = response.tradingName ?? response.name;
                    this.locationCount = response.licensedLocCount;
                    this.employeeCount = response.licensedEmpCount;
                    //here we set the contract end date to use
                    this.contractEndDate = response.contractEndDate;
                
                    sessionStorage.setItem("contractEndDate",this.contractEndDate.toString());
                    if (response.contractEndDate && response.contractEndDate > 0) {
                        this.selectedExpiryDate = this.expiryDates[3];
                        this.dateSelect(this.selectedExpiryDate);
                    }
                } else {
                    this.modalService.showInfoPopup({ title: 'Ooops!', text: 'Customer missing.', showIcon: true, popupType: PopupTypes.Error });
                }
            },
                (error: any) => {
                    this.modalService.showInfoPopup({ title: 'Ooops!', text: error, showIcon: true, popupType: PopupTypes.Error });
                });
    }

An additional @Input function is defined in this component:

      public itemDisabled(itemArgs: { dataItem: IdNameValue; index: number; date: number})  {

        console.log(this.contractEndDate)
   
        if ((this.contractEndDate)) {
            if (itemArgs.dataItem.id === LicensePeriod.ContractEndDate) {
                return true;
            }
        }
        return false;
    }

However, when trying to access the itemDisabled function, this.contractEndDate appears as undefined, even though its value had been previously set.

Answer №1

The reason for this issue in your scenario is due to the fact that the itemDisabled function is being invoked from a different context (and another this).

To fix this problem, you have two options:

  • Switch the function to an arrow function instead of a regular function:
public itemDisabled = (itemArgs: {
  dataItem: IdNameValue;
  index: number;
  date: number;
}) => {
  console.log(this.contractEndDate);

  if (this.contractEndDate) {
    if (itemArgs.dataItem.id === LicensePeriod.ContractEndDate) {
      return true;
    }
  }
  return false;
};
  • Or bind your function to this associated with your component:
<hf-shared-dropdown-small
  class="license-card__row-input"
  [id]="'expiryDate'"
  [required]="false"
  [itemDisabled]="itemDisabled.bind(this)"
  [isConfirmable]="false"
  [data]="expiryDates"
  [value]="selectedExpiryDate"
  (valueChange)="dateSelect($event)"
>
</hf-shared-dropdown-small>

For more information on the distinction between the arrow function and the normal one, refer to:

Answer №2

Within the license-add.component.html file, you have only included [itemDisabled]="itemDisabled"

Perhaps consider using [itemDisabled]="itemDisabled()" with your itemArgs object?

I believe the issue lies in not utilizing your itemArgs in the HTML.

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

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

angular datatable pagination issue with mdb

I've been following a tutorial at this website: Unfortunately, I keep encountering an error whenever I attempt to use pagination. Cannot read property 'setMaxVisibleItemsNumberTo' of undefined This is how my HTML code looks: <table ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

Integrate a formcontrol within a specialized directive

I am looking to develop a directive that can alter a host element when a form control is invalid. Here's an example in code: <div [appFormControlValidate]="email"> <!-- email is the form control I want to use --> <input type="email" ...

Apollo useQuery enables risky array destructuring of a tuple element containing any value

Currently, I am incorporating TypeScript into my project and have a GraphQL query definition that utilizes Apollo's useQuery. According to the documentation, the call should be typed, however, I am encountering an ESLint error regarding data being ass ...

Is it possible to denote two "any" as the same thing in a TypeScript function signature?

Here is a function to extract items from an array based on a checker function: function extractItemsFromArray(array: any[], isItemToBeRemoved: (item: any) => boolean) { let removedItems = []; let i = array.length; while(i--) if(isItemToBeRemo ...

Angular2 encounters an error when processing a custom HTTP request

I offer two unique services Custom HTTP client service fetch(url):any{ this.storage.fetchData('auth-token').then((token) => { let headers = new Headers(); this.prepareHeaders(headers); return this.http.fetch(url+"?token="+toke ...

Trouble encountered during installation of Angular CLI: module.js - code 549

I recently encountered issues with Angular-CLI, so I decided to update it using the command $ npm install -g @angular/cli. However, after doing so, I am facing a new error message. Can anyone provide assistance with this problem? module.js:549 throw err ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

I am experiencing an issue with my post method where I am not receiving any data back from the

I am using a POST method to send data to the server and I want to receive data back after that. When I subscribe to the post method: this.categoryService.storeCategory(this.currentFileUpload, this.category).subscribe(category => { console.log(" ...

When the data is not initialized within the ngOnInit() function, the p-dataTable does not bind properly

In the process of building a form, there is a specific dialog available for users to input data. The dialog functions within a larger form structure. Once the user finishes entering their data in the dialog and clicks on the SAVE button, the entered inform ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Extending Error object disrupts `instanceof` validation in TypeScript

Could someone clarify why the error instanceof CustomError part of the code below returns false? class CustomError extends Error {} const error = new CustomError(); console.log(error instanceof Error); // true console.log(error instanceof CustomError); ...

Angular 6: Exploring the Power of Nested HTTP Requests

Trying to figure out how to successfully execute a nested HTTP call in Angular 6. My goal is to loop through an array and make two server-side calls, purging data from both responses. Looking for the most efficient solution to achieve this as my current co ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Utilizing Conditional Styling for an Array of Objects within a Textarea in Angular 6

My array contains objects structured as follows: list =[ { name:"name1", value:true } { name:"name2", value:false } { name:"name3", value:true } { name:"name4", value:false ...

What allows us to create an instance of a generic class even without defining the generic type parameter?

It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter. For instance, in the code snippet below, the class Foo includes a generic type parameter T. However, when creating a new Foo i ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

How can one properly conduct a health check on a Twilio connection using TypeScript?

How can I create an endpoint in TypeScript to verify if the Twilio connection is properly established? What would be the proper method to perform this check? Below is a snippet of my current code: private twilioClient: Twilio; ... async checkTwilio() { ...

`How can I enhance the appearance of an Angular 4 component using an attribute?`

There is a component where I need to pass specific data to the child components within an ngFor loop using attributes. Depending on the attribute, I want to style these child components accordingly. Code testimonials.component.html - (Parent component) ...