Referencing 'this' in Angular and Typescript: Best practices

When setting up TypeScript in an Angular project, I use the following syntax to declare a controller:


module app {

    class MyController {
        public myvar: boolean;

        constructor() {
            this.myvar= false;
        }
    }
    angular.module("app").controller("MainController", [MainController]);
}

It's important to note that I prefer not to inject the scope and instead utilize inner properties/methods of the controller. However, I find accessing properties with 'this' to be cumbersome. Typically, I would have to declare:

var vm = this.
vm.myvar = ...

This becomes repetitive as I have many methods; each one requiring the 'vm' declaration. Are there any best practices or patterns for declaring 'vm' only once?

Answer №1

Instead of accessing properties with 'this' and declaring var vm = this, is there a more efficient way to declare 'vm' only once?

It's advisable to rethink that practice. In TypeScript, it's simpler to utilize this directly without assigning it to a variable—it's readily available for use.

The trick here is to utilize arrow functions to always refer to the class instance's this and not the this linked to a regular function expression.

class MyController {
    myVar = false;

    someOtherMethod() {
        // good
        functionWithCallback(() => {
            // this will be the class instance
            console.log(this.myVar);
        });

        // bad
        functionWithCallback(function() {
            // this will not be the class instance
            console.log(this.myVar);
        });

        // good
        functionWithCallback(() => this.myOtherMethod());

        // bad, `this` in myOtherMethod is not the class instance
        functionWithCallback(this.myOtherMethod);
    }

    myOtherMethod() {
        console.log(this.myVar);
    }
}

function functionWithCallback(callback: Function) {
    callback();
}

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

Error message displaying 'class-transformer returning undefined'

I'm new to working with the class-transformer library. I have a simple Product class and JSON string set up to load a Product object. However, I'm encountering an issue where even though I can see the output indicating that the transformation was ...

The reset function in Angular's template-driven form does not seem to be functioning properly when implemented using a component

Form Template Example <form #contactFormTemplate = "ngForm" (ngSubmit)="submitContactForm()"> <input type="text" class="form-control" name="name" [(ngModel)]="formData.name" ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Tips for utilizing a formatter with a Doughnut chart in Angular using Chart.js

When using Chart.js with AngularJS, I tried to display numbers or percentages in a doughnut chart using a formatter. However, it did not work as expected. Here is how I implemented it in my HTML: <canvas baseChart class="chart" [data]="do ...

The absence of an 'Access-Control-Allow-Origin' header on the requested resource prohibits access from the origin 'localhost:8080'

I have encountered this problem multiple times on various forums, but so far none of the suggested solutions have worked for me. Currently, I am developing a MEAN stack application that utilizes PassportJS for Twitter login functionality. angular.module( ...

What is causing the issue with AngularJS Routing Concept in Notepad++?

When using Notepad++, I encountered an issue where Angular Routing tools were not functioning properly. Despite attempting to link all the necessary angular routes, the problem persisted. Interestingly, the Angular tutorial provided by Scotch Tutorials wo ...

Utilize an array as the response model in Amazon API Gateway using the AWS CDK

I am currently in the process of developing a TypeScript AWS CDK to set up an API Gateway along with its own Swagger documentation. One of the requirements is to create a simple endpoint that returns a list of "Supplier", but I am facing challenges in spec ...

Accessing Route Data in Angular's AppComponent

In my app-routing.module.ts file, I have set up the following routes: const routes: Routes = [ { path: 'abc/:id', component: AbcComponent, data: { category: 'Public' } }, { path: 'xyz/:id/tester/:mapId', componen ...

Unlock the full potential of working with TaskEither by utilizing its powerful functionality in wrapping an Option with

After exploring various examples of using TaskEither for tasks like making HTTP requests or reading files, I am now attempting to simulate the process of retrieving an item from a database by its ID. The possible outcomes of this operation could be: The i ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Conceal the name of a property when displaying it

I have a function that retrieves data from an interface, which includes a property called name. Currently, the output includes the property name, but I would like to remove it if possible. How can I achieve this? Here is the interface structure: export i ...

Is it possible to pass a prop from a parent container to children without knowing their identities?

I am currently working on a collapsible container component that can be reused for different sections of a form to display fields or a summary. Each container would include a Form object passed as a child. Here is the basic structure of my code: function C ...

Attempting to assign a value in ng-init that was only established after loading the model and making two AJAX calls

Let me explain, The project I'm currently working on involves a spinoff of phonegap. I am facing a situation where I need to wait for an AJAX response before setting the ng-init value. Typically, you can set it like this: ng-init = "ng-model = arr[0] ...

What is the purpose of manually creating the vscode.d.ts file in the vscode source code?

Manually writing .d.ts files is typically only necessary when working with existing .js files. If you're developing a TypeScript project, it's recommended not to write .d.ts files by hand, as the compiler with the --declaration option can auto-ge ...

AngularJS table not properly sorting date and time

After retrieving some data from my backend, I am facing an issue with sorting the date column in an angularjs table. Instead of sorting based on the full date format, it seems to be using the formatted date string that was generated using a date filter. S ...

Can a function's return type be set to match the return type of its callback function?

Check out the following function export const tryAsyncAwait = async (fn: () => any) => { try { const data = await fn(); return [data, null]; } catch (error) { return [null, error]; } }; If I use this function as an example... const ...

When invoked, the function Subscribe() does not have a

Currently, I am facing an issue where I cannot use the result obtained from subscribe() outside of the subscribe function. Whenever I try to console.log the result, it always shows up as undefined. My suspicion is that this might be related to the asynch ...

AngularJS - Executing code after the entire application has finished loading

Being new to AngularJs (1.6), I am just starting out and may not have all the right questions yet. I have recently begun working on a project built with AngularJS 1.6. My current task involves running a script on specific routes. For now, let's cons ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...