What is the best way to access variables within a function from an external function in Typecript?

On my HTML page, I am invoking a method with parameters using the onchange event. Once I retrieve the value, I trigger function2 on the click of another button. I am looking to access the variable from function in function2 within the same class. My implementation is based on Angular 6 and TypeScript. Below is a snippet of my TypeScript file:

 
export class Component extends Lifecycle {
  cc1: string;
  constructor (){}
  Function (cc1, cc2)
  {
   this.cc1 = cc1;
   // return cc1;
   }

  Function2 (){
      console.log(cc1);
    }
  }

Could someone provide assistance on this matter?

Answer №1

Utilize the this keyword within a method to access properties or methods specific to the class.

export class customComponent extends Lifecycle {
    property1: string;
        constructor() {
        super();
    }
    method1(property1, property2) {
        this.property1 = property1;
        // return property1;
    }

    method2() {
        console.log(this.property1);
    }
}

Remember to invoke super when extending the class.

Answer №2

When working with Function2, you will utilize this.cc1 as illustrated below (please note that I have modified the parameters passed to Function1 to avoid confusion with the class-level variable)

export class component extends Lifecycle {
  cc1: string;

  constructor () {
    super();
  }

  Function1 (_cc1, _cc2) {
    this.cc1 = _cc1;
  }

  Function2 () {
    console.log(this.cc1);
  }
}

Answer №3

Inside the second Function

SecondFunction (){
      console.log(this.cc1);
    }
  }

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

Is it possible to deactivate the click event on an Angular mat table row?

Within my Angular mat table, I have implemented code that expands a table row when clicked. However, I now need to prevent certain rows from being clickable based on the "element.disable" property. <ng-container matColumnDef="id"> <th mat-hea ...

retrieving information and parsing from an API using Ionic and Angular version 4

How can I extract data from the "data" field in my API using a function? getMenu() { return this.http.get('http://site.dev/api/menu/7'); } { "id": 26, "name": "Default", "title": "default", "pageelements": [ { "id": 15, ...

Using TypeScript generics to constrain to either a number or a string

I am working on coding a react input component that accepts a defaultValue parameter of type string | number. This component has a state type matching the type of the received defaultValue; This is my code: type TypeName<T> = T extends number ? "nu ...

ElevationScroll expects the 'children' prop to be a single child component of type 'ReactElement<any, string>'

I am currently working on integrating the Elevate AppBar from Material UI into my application using the following code: interface Props { children: React.ReactElement; } export const ElevationScroll = ({children}: Props) => { const trigger = u ...

Using the Angular Slice Pipe to Show Line Breaks or Any Custom Delimiter

Is there a way in Angular Slice Pipe to display a new line or any other delimited separator instead of commas when separating an array like 'Michelle', 'Joe', 'Alex'? Can you choose the separator such as NewLine, / , ; etc? ...

Retrieving the component's values when utilizing the `<ng-content>` directive

Seeking a technique for accessing the values of a component when utilizing <ng-content>: import {Component} from '@angular/core'; @Component({ selector: 'home-page', template: `<person-box>{{name}}</person-box> & ...

Experiencing difficulty in triggering a NextUI Modal by clicking on a NextUI Table Row

In the process of developing my web portfolio, I am utilizing NextJS, TypeScript, and TailwindCSS. A key feature on my site involves displaying a list of books I have read along with my ratings using a NextUI table. To visualize this functionality, you can ...

Resolve the error message "Class is not a constructor" which arises while utilizing namespaces in TypeScript with WebPack

Issue with TypeScript Namespaces in PIXI.js As I delve into the world of TypeScript and PIXI.js without any framework, I find myself facing a challenge. Previously, at work, we utilized namespaces with the module keyword for a cleaner structure. However, ...

Encountered an issue while trying to install npm for an existing Angular 4 project

As a newcomer to angular 4, I attempted to import an existing project into my local machine. Using npm install to fetch the nodes_modules as per the package.json of the project, resulted in the following error: https://i.sstatic.net/pj52Q.png Here is the ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

What prevents me from employing my nestjs unique decorator within a constructor?

I am looking to develop a personalized decorator that fetches tenant information. This is the current code snippet I have: export type TenantInfo = { token: string id: string } export const TenantInfo = createParamDecorator( (data: unknown, cont ...

Angular8 with the [tinymce] library for customizing editor elements and configuring multiline options

I am currently working with Angular 8 and in the template, we have the following code snippet: <editor required class="research-modal__control__input research-modal__control__input__description" formCo ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...

Mastering the Art of Sharing PrimgNg Selected Checkboxes with Child Component Dropdown

I am developing a simple application using PrimeNg. In order to pass information from the selected items of a Multi-Select component in the parent element (<p-multiSelect/>) to a Dropdown component in the child element (<p-dropdown/>), I have i ...

The Angular 2 UI is unable to successfully connect with the controller through the API call

When attempting to call a URL from Angular 2 using http.get(), an exception is being thrown and the debugger in the controller is not being hit. Although I have checked the proxy and routing, they are the same as my existing projects. This new project is c ...

bespoke feature for conducting raw queries within the Laravel environment

Can someone guide me on where to add a custom function in the Laravel framework or if there is something missing in the installation? I am working on implementing the following function: public function select($query, $bindings = array()) { return $th ...

Error: Angular SSR does not recognize IDBIndex

Attempting to build my Angular application using the command npm run build:ssr. The application built successfully, but when running the command npm run serve:ssr, I encounter the following error: ReferenceError: IDBIndex is not defined Note: Upon invest ...

Is it possible to override CSS classes in Ionic without using app.scss?

I'm currently working on designing a dark theme for my ionic application by watching this tutorial. It's been effective for most of the classes, however, I've encountered some CSS classes that only respond to overrides in app.scss. If I try ...

Exploring the narrowing capabilities of TypeScript within while loops

When I write while loops, there are times when I know for sure that a certain value exists (connection in this case), but the control flow analysis is unable to narrow it down. Here's an illustration: removeVertex(vertex: string) { const c ...