0

I am exporting a component that has 2 variables, and 2 functions to change those variables (which are booleans).

Now when I trigger my function with (click) I get the error:

ORIGINAL EXCEPTION: ReferenceError: landing is not defined

but If I define landing and portfolio as variables ie var landing = true; I can't evaluate them with *ngIf

This is the export of my component:

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

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

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

I am new to typescript and Angular2 and have no idea what I'm doing wrong. In Angular1 I'd just acces them with $scope.

2 Answers 2

1

You need to use 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's because landing and portfolio are part of the class (properties). It's the same for methods.

Within the template associated with the component, you don't need the this keyword since Angular2 will automatically look into the properties and methods of the component class when evaluating expressions. Only elements associated with the component can be used in expressions...

Sign up to request clarification or add additional context in comments.

Comments

1

This should do what you want:

export class NavigationComponent {
    landing:boolean = false; // `:boolean` is not necessary but improves feedback from the IDE 
    portfolio::boolean = true;

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

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

1 Comment

once landing variable initialize with false/true value(IDE will consider it as a bool), so anyways IDE will provide tooling for it.. but having datatype with declaration is good to have

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.