When attempting to invoke a view model function of a component from external sources in Aurelia with TypeScript, an error message may appear stating "Property of undefined cannot be read

My expectation was that using view-model.ref would allow me to access the viewmodel of a component from outside the component and call its functions.

The following code leads to an error message: "Cannot read property 'LoadForAdditionalLocations' of undefined."

Component being Imported

export class UserLocationSelector {
    public LoadForAdditionalLocations(reportLogin:string, addLocationsLogin:string){
        ///do stuff
    }
}

Page where the component is used (TypeScript file)

export class AddLocation{
    attached(){
        this.UserLocationSelector.LoadForAdditionalLocations("user1","user2");
    }
}

Page where the component is used (HTML file)

<template>
    <require from='user-location-selector'></require>
    <div>
         <user-location-selector view-model.ref="UserLocationSelector"></user-location-selector>
    </div>
</template>

Answer №1

Ensure that the name assigned to the ref attribute will become a property on your VM and should be accessed using this.. Therefore, it is advisable to stick to JavaScript naming conventions.

Importing Component

export class UserLocationSelector {
    public loadForAdditionalLocations(reportLogin:string, addLocationsLogin:string){
        ///do stuff
    }
}

TS File - Page containing the component

export class AddLocation{
    userLocationSelector;

    attached(){
        this.userLocationSelector.loadForAdditionalLocations("user1","user2");
    }
}

HTML File - Page containing the component

<template>
    <require from='user-location-selector'></require>
    <div>
         <user-location-selector view-model.ref="userLocationSelector"></user-location-selector>
    </div>
</template>

For detailed code example, check out this gist:

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

Designing a Tombstone with TypeScript

In TypeScript, I have certain values that are only necessary within the type system and not at runtime. I am seeking a way to void these values without losing their type information. The function bury illustrated below is intended to replace the actual v ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

Adding up nested arrays based on their respective indices

If I have two nested arrays within a corresponding array like this: const nums = [ [4, 23, 20, 23, 6, 8, 4, 0], // Each array consists of 8 items [7, 5, 2, 2, 0, 0, 0, 0] ]; How can I add the values based on their indexes? Expected Result: ...

parsing objects within an HTML component in Angular

Is there a way to utilize an object as the @input parameter in HTML? For example: <app-home [param]="user.salary"></app-home> However, the type of my user object is structured like this: user:Person=new Employee(); The classes invol ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API. <a [routerLink]="['/usedCars/detail', list ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...

Trouble navigating through an index of elastic data? Learn how to smoothly scroll with Typescript in conjunction with

I'm currently using the JavaScript client for Elasticsearch to index and search my data, but I've encountered an issue with using the scroll method. Although I can't seem to set the correct index, I am confident in my technique because I am ...

Accessing the right-click menu in Angular will also open the browser's native

I need to implement a right-click functionality in my component. Here is the code snippet: (contextmenu)="openNote(i)" This code opens a popup when I perform a right-click. The issue I'm facing is that when I right-click, it triggers both my custom ...

A guide on resolving TypeScript monorepo webpack loader problems

I recently created a typescript monorepo here with the following organized folder structure: . └── packages ├── package.json // Contains the monorepo workspace configuration ├── web-app // Includes the NextJS website files └ ...

Transfer the data from one object to another while disregarding any additional properties

I am dealing with 2 objects: person{ name : string gender : string } woman{ name : string } The challenge I face is that I have an object "person" filled with values, and I need to copy those values into a new object "woman" without including the "ge ...

Can you explain the meaning of { [key: string]: boolean; } data type?

Have you come across this function declaration recently? static required(control: AbstractControl): { [key: string]: boolean; }; What does the return value of this function mean? It seems to be returning an object with multiple properties, each c ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

Aligning arguments within the function signature

Is it possible to specify in TypeScript that the method 'foo' always expects FooData, etc. for the following code snippet: const search = (data: FooData|BarData|BazData, method:"foo"|"bar"|"baz") => { //Perform some common operations retu ...

Every time I execute my program, it consistently displays a 500 error message when using both the POST and GET

I'm seeking assistance with mvvm as I am new to it. Can anyone help me in displaying details based on the selected date? Upon running my code, I encounter a 500 error with both the post and get methods. Schedule.cshtml <div class="col-lg-8" ng-ap ...

Implementing a global provider in Ionic 3

I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status. Following this guide, I included the class in my app.module.ts file to ensure it functions as a global ...

Difficulty encountered when assigning a value to an array within an object derived from a class

Within my Angular project, I've created a class: export class Test { mcq: { question: string, options:string[]}[] = []; } //outline of an object containing a question and an array of strings In another component where I import this class, I want t ...

Retrieving a data type from the key values of deeply nested objects

I'm currently working with JSON data that contains nested objects, and my goal is to extract the unique set of second-level keys as a type. For instance: const json = { 'alice': { 'dogs': 1, 'birds': 4 ...