What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this:

export class myapp {
  detail;

  myarr = ['me', 'myself', 'i'];
  title = this.myarr[0];
  this.detail = this.title ;  //error
}

I'm curious why `this.detail` is not allowed but `this.title` is allowed. Why do I need to create a new variable? Can't I use a variable that's already in the class?

Answer ā„–1

When working inside a class but outside of methods, your options are limited to initializing fields or declaring methods. Adding arbitrary statements in this context is not allowed.

To perform additional tasks, you can utilize the constructor().

export class myapp{
  detail : string = 'I am';

  myarr = ['me', 'myself', 'i'];
  title = this.myarr[0];
  constructor() {
    this.detail = this.title ;  
  }
}

Answer ā„–2

When working in your specific case, there is no need to redeclare the class member...

export class myapp{
    myarr = ['me', 'myself', 'i'];
    title = this.myarr[0];
    detail = this.title ;
}

What is the purpose of TypeScript in this scenario?

TypeScript serves to alert you to the possibility that you have inadvertently declared a duplicate member by preventing such actions.

It is worth mentioning that using the this prefix for members within a class is not necessary. The resulting JavaScript code will include them...

var myapp = (function () {
    function myapp() {
        this.myarr = ['me', 'myself', 'i'];
        this.title = this.myarr[0];
        this.detail = this.title;
    }
    return myapp;
}());

You can specify an access modifier for the members, as they default to private.

export class myapp{
    private myarr = ['me', 'myself', 'i'];
    protected title = this.myarr[0];
    public detail = this.title ;
}

Access modifiers are only enforced during compile time.

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

Developing an Observer and sending updates to my followers

I have a function that returns an Observer for subscription. Inside this function, I make an API call which also returns an Observer to which I subscribe. Once I analyze the data received from this Observer, I need to notify my own Observer subscribers. B ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...

The ng-repeat functionality in Angular 2 is not functioning correctly when trying to select an option from an array of objects. Instead of displaying the actual object, it is

When using ngRepeat in Angular 2, I have found that selecting options from an array of strings works perfectly fine. However, when the data is an array of objects, the ngModel displays '[Object object]' instead of the selected object. I have trie ...

Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code... <select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)"> <option *ngFor="let menu_optional of menu_optionals" value= ...

Exploring Angular's wild comparison capabilities for strings within HTML documents

I have a question that may seem basic, but I am curious if it is possible to use wildcards in *ngIf comparisons. Consider the following code snippet: <ng-container *ngIf="test == 'teststring'"> </ng-container> I am wonder ...

Adal TypeScript Document

Recently, I've been experimenting with the TypeScript version of adal.js. As part of my setup process, I'm referring to this link to install adal.ts. However, after executing the command: npm install adal-typescript --save a new "node_modules" ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

Utilizing an image as a background using [ngStyle] in Angular 5

I attempted to set the background of a Div element with an image saved in the database using [ngStyle] in Angular, but unfortunately it did not work as expected. <div class="image" [ngStyle]="{'background': ' url(' + imageUrl + &ap ...

The HAProxy is encountering difficulties when trying to connect to port 80 for the Angular application that is currently running on

I currently have an Angular application running on port 4200, and I have implemented HAProxy as a reverse proxy to redirect all traffic from port 80 to 4200. However, while my HAProxy settings are correctly directing traffic from 8080 to 4200, the redire ...

Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away. This is how it's done in app.config.ts: export const appConfig: ApplicationConfig = { providers: [ ConfigService, ... { pr ...

What is the best way to extract data from API console output using Angular?

Currently, I am deeply involved in a full stack project utilizing asp.net and angularjs. My goal is to extract output response from the Swagger API. You can view the code I've written for this purpose here: (https://i.stack.imgur.com/vLyIE.png) The A ...

Encountering a tslint issue: "Parsing error: Expression expected"

Could someone provide some insight on this issue? Iā€™m encountering an error message that says Failed to compile. Parsing error: Expression expected with this specific line of code - isLogViewVisible: dashboard?.logView !== null where the variable isLog ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

What is the best way to search for a specific value in the Record definition?

In the documentation for Typescript, a type is defined to be used as keys into a Record<>. It seems like this is done to restrict and secure the keys that can be utilized. type CatName = "miffy" | "boris" | "mordred"; W ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

It is not possible to execute an injectable function using a service instance, as the parameter value consistently stays as null

I am utilizing an angular web app that relies on access tokens that have the potential to expire. When they do expire, a 401 status response is sent back to the app, triggering processing by a retryWhen operator. The logic for initiating a token refresh AP ...

Populate choices in the mat-select dropdown

I am encountering an issue with two-way binding in the mat-select component from Angular Material. In my TypeScript file, I have an option list and a variable for binding called valueFromDB. When I choose a value in the mat-select component, it automatical ...

Angular 2 Endgame: HostBinding feature no longer functional

Here is how I used host-binding on a button attribute named "disabled" in the parent component of ng2-RC4: @Component({ selector: "nav-next", template: ` <div class="nav-next-directive" (click)="onClick($event)"> <button color ...