Retrieve a constant value set in the OnInit method when a specific event occurs

I'm struggling to log the name value on a click event. Can you please provide some guidance? This is inside the .ts file:

export class ScrolldemoComponent implements OnInit {

      constructor() { }

      ngOnInit() {
        const name = "test";
      }

      myEvent(event) {
        console.log(name);
      }

    }

This is inside the HTML:

<button (click)="myEvent()">My Button</button>

Answer №1

Implement it within the component's scope

title:string = 'example'
 ngOnChanges() {
    this.title = "changed";
  }

  triggerEvent(event) {
    console.log(this.title);
  }

Answer №2

When using the "const" keyword, variables are block-scoped meaning they only exist within the innermost block they are declared in.

Therefore, if you declare a variable inside a function like "ngOnInit", you will not be able to access it outside of that function. It is recommended to define such variables at the component level as advised by Aravind.

Answer №3

To ensure easy access to a variable across different functions, it is advisable to create a global variable and initialize its value within the ngOnInit lifecycle hook. It's important to note that const, let, and var are all block-specific types of variables. For further guidance on this topic, you can review Aravind's example code where he opted to utilize a global function instead of a block-specific variable.

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

When attempting to upgrade from Angular 10 to 13, users may encounter the following error message: "TS2307: Unable to locate module 'path_to_service' or its corresponding type declarations."

I initially developed my Angular App using the paper-dashboard template with Angular version 10.0. Recently, I upgraded to Angular version 13 and switched to a different template - WrapPixel. However, I encountered an error when trying to include a servi ...

What sets apart a JSON Key that is enclosed in double quotes "" from one that has no quotes?

Below is my TypeScript object: { first_name:"test", last_name: "test", birthdate:"2018-01-08T16:00:00.000Z", contactNumber: "12312312312", email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e19 ...

Running a Spring Boot backend alongside multiple frontends on the same Tomcat server

I have a unique scenario where I have access to only one Tomcat server and need to set up the following components: A Spring Boot service that handles CRUD operations on a database through a REST API 2-3 distinct Angular frontends that interact with the R ...

How can I ensure a module in Angular module federation v14 is only loaded in either the parent or child app, but not both?

I am currently utilizing Angular 14 along with module federation in my project. Within my child application, I have the following configuration: module.exports = withModuleFederationPlugin({ name: 'childapp', exposes: { './app1&apos ...

Angular downgrades from version 13.3.8 to 13.3.7

When I input the command: ng v I am shown the version as "Angular: 13.3.8" in the image. Can someone explain where this version is coming from and how can I change it back to 13.3.7? Furthermore, I noticed that the packages listed in the screenshot are d ...

Can you guide me on how to specify the return type in NestJS for the Session User in a request?

async authenticated(@Req() request: Request) { const user = request.user return user } It is important for the 'user' variable to have the correct type globally. While working with express passport, I came across the following: decl ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

Subscribe again to an observable from a header module

Within my Angular service, I have an Observable that showcases a countdown timer for a user's e-commerce order when they reach a specific route after adding items to their cart. Although it functions correctly the first time an order is initiated, if ...

How can you properly expand TypeScript definitions within an external library?

I am currently utilizing TypeScript version 4.5.5 In a third-party library called dva, there is an interface named DvaInstance within the existing index.d.ts file: export interface DvaInstance { // ... } export { connect, connectAdvanced, useSelector ...

What is the best way to format this DateTime for a more visually appealing appearance within an Angular Material <mat-card-subtitle>?

My date looks like this: 2000-12-16T00:00:00 When displayed in Material code (as the publish_date): <mat-card *ngFor="let book of bookItems"> <mat-card-header > <mat-card-title>{{book.title | titlecase}}</mat-card-title> ...

Receiving information from the Angular server located at IP address 127.0.0.1

Working on a project that utilizes Ionic, Angular, NodeJS, and Express. Seeking to fetch data from an application on my laptop located at: Currently using a proxy for local development, but unsure how to handle this after deploying to Heroku. Seeking gui ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

[Simple TypeScript]: Assign the parameter value as the key of the object returned by the function

How do I modify the key of a function returned object to match its parameter's value? Here is my current code: const createCache = <A, T extends string>(name: T, base = {}) => { const cache = base; return { [name]: cache, } as { ...

Exploring Vue 3.3: Understanding Generics and Dynamic Properties

I'm currently diving into the generics feature in vue 3.3 and I've been pondering about defining the type of an incoming prop based on another prop value. This is my current component structure: export interface OptionProps { id: string | numb ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

mat-sidenav is exempt from the fxFlex rules

Having trouble centering the content within . I've attempted various rules but nothing seems to be working. Interestingly, when I apply fxFlex rules to , everything falls into place perfectly. I've gone through trying to set rules for each elemen ...

Utilizing prerender.io with lazy loading in Angular 2: A comprehensive guide

As Angular Universal is not expected to be included in the CLI for some time, I've had to resort to using prerender.io in order to ensure proper SEO functionality. However, my tests have shown that there are issues with lazy loaded modules causing SEO ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Is it possible to generate type definitions for inner classes?

I'm currently exploring the usage of TypeScript within a Salesforce project involving RemoteObject One challenge I'm facing is creating typings for the external JavaScript object syntax. For example, in JavaScript: var ct = new RemoteObjectMod ...