Exploring variables in Angular2 with TypeScript

I have a component that I am exporting with 2 variables and 2 functions to toggle those variables (which are booleans).

However, when I trigger my function using (click), I encounter the following error:

ERROR: ReferenceError: 'landing' is not defined.

If I define 'landing' and 'portfolio' as variables using var landing = true;, I cannot evaluate them with *ngIf.

Here is the code snippet for my exported component:

export class NavigationComponent {
    landing = false;
    portfolio = true;

    changeMiniNavLanding = function() {
       landing = true;
       portfolio = false;
    }

    changeMiniNavPortfolio = function() {
       landing = false;
       portfolio = true;
    }
}

As someone new to TypeScript and Angular2, I'm unsure of what mistake I may be making. In Angular1, I would simply access them via $scope.

Answer №1

To properly reference the properties and methods within a class, utilize the this keyword:

export class NavigationComponent {
  landing = false;
  portfolio = true;

  changeMiniNavLanding() {
    this.landing = true;
    this.portfolio = false;
  }

  changeMiniNavPortfoliofunction() {
    this.landing = false;
    this.portfolio = true;
  }
}

It is important to use this since landing and portfolio are integral components of the class itself. This principle applies to both properties and methods.

When working within the component's associated template in Angular2, including the this keyword is unnecessary as Angular2 inherently searches for properties and methods within the component class during expression evaluation. Only elements connected to the component can be utilized within expressions...

Answer №2

Here is the solution you're looking for:

export class NavigationComponent {
    landingActive:boolean = false; // `:boolean` is optional but recommended for better code clarity
    portfolioActive::boolean = true;

    toggleLandingNav() {
       this.landingActive = true;
       this.portfolioActive = false;
    }

    togglePortfolioNav() {
       this.landingActive = false;
       this.portfolioActive = true;
    }
}

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

Creating an Observable from static data in Angular that resembles an HTTP request

I have a service with the following method: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observable<string> { i ...

Angular 6: Endlessly Scroll in Both Directions with Containers

Does anyone know of a library for angular 6 that allows for the creation of a scrollable container that can be scrolled indefinitely in both directions? The content within this container would need to be generated dynamically through code. For example, ...

Sending data from an Angular 2 application to a Spring MVC Rest API using HTTP POST method

I'm encountering an issue while attempting to perform an angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam. Despite my efforts of searching for a solution, I have not been successful in binding it to my object. I even ...

Using the $state feature in TypeScript with Svelte 5 for defining class fields

Currently, I have a class implementation as follows: class TestClass { prop = $state('test'); } This code works smoothly in files with the extension .svelte.js, and .svelte using <script lang="js">, but encounters issues in f ...

"Implement ngx-translate to cater to multi-language support in your Angular library

How can I effectively incorporate ngx-translate for handling translations within an Angular library? I have been experimenting with various methods, but have yet to find a successful solution. ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

Tips for sending an Angular http post request including both data and an image:

When making a post request in Angular, I typically send data (such as 'product' data) using an object like this: product: any = {}; // filled with properties (code, barcode, name, description...) and then include it in the request: return this.h ...

Error when using Angular CLI: npm error! The call stack size has exceeded the limit

While attempting to develop an Angular app using ng new testApp -routing, I encountered the following error. Command: ng new testApp -routing Error: npm ERR! Maximum call stack size exceeded Does anyone have a possible solution for this issue? ...

Angular 2, Release Candidate 5 - Dropdown form includes mysterious "phantom" choice

While working with Angular 2, RC 5, I have encountered a strange issue while building a form to create a new model object. The problem arises when there is an extra blank <option> appearing in the dropdown list after transpiling the code, even though ...

Children components are not re-rendered by React

I created a basic task manager, but I'm encountering issues when trying to manage all the data from a single point within the TaskManager component. Essentially, I have a TaskManager component that acts as the container for all the data. Within this ...

Arranging elements within a card using CSS

I'm currently facing a dilemma regarding the arrangement of elements within the card. My goal is to have the items inside the "top-right-element" class positioned in the top right corner, while the button featuring the pi-chevron-up icon should be pla ...

Implementing Bootstrap 5 within Angular 14 and incorporating SCSS styling

Currently, I am in the process of integrating Bootstrap 5 into my Angular 14 project, which utilizes SCSS instead of CSS. After successfully installing Bootstrap via npm (npm install bootstrap --save), the package is properly listed in my package.json file ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

Can the hexadecimal value from an input type color be extracted and used to populate form fields that will then be displayed in a table after submission?

Hello everyone, I'm new to this platform and seeking guidance on how to improve my post! I recently created a CRUD app using Angular. It consists of a basic form with 4 fields, a color picker using input type='color', and a submit button. U ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

Error encountered while attempting to globally install TypeScript using npm: "npm ERR! code -13"

Issue with npm error 13 Having trouble installing typescript-g package Error details: - errno: -13, - npm ERR! code: 'EACCES', - npm ERR! syscall: 'symlink', - npm ERR! path: '../lib/node_modules/typescript/bin/tsc', ...

Error encountered when trying to access Proxy Object or Object[] in MobX with TypeScript

In my MobX Store, I have a straightforward structure: import { observable, action, makeObservable } from "mobx" import { BoxShadow, ShadowValues } from "./types" import { boxShadow } from "./constants" interface IStore { ...

What could be causing my application to experience slow build times when using ng serve?

I am experiencing a frustratingly slow compilation and output result when making changes. Currently, my ng serve command takes about 20 seconds to update after a simple text modification in a file. The actual compilation time is quick, around 3-5 seconds, ...

Enhanced auto-completion for Nativescript Android with TypeScript

Are there any available d.ts or Nativescript plugin files that offer code completion and IntelliSense for the Android API when using TypeScript? It seems like it should be relatively straightforward to generate one from the Android docs, but I'd prefe ...

What is the best way to convert canvas data into a string in Angular once the user has made a drawing on it?

I need help figuring out how to automatically store canvas data to a variable in Angular whenever the user draws or makes changes to it. Here is a snippet from my component.html file: <canvas id="canvas"></canvas> And here is part o ...