【问题标题】:Angular2; typescript - accessing variables角2;打字稿 - 访问变量
【发布时间】:2016-03-30 09:23:45
【问题描述】:

我正在导出一个具有 2 个变量和 2 个函数来更改这些变量(它们是布尔值)的组件。

现在,当我使用 (click) 触发我的函数时,我得到了错误:

原始异常:ReferenceError:未定义着陆

但如果我将着陆和投资组合定义为变量,即 var landing = true;,我无法使用 *ngIf 评估它们

这是我的组件的导出:

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

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

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

我是 typescript 和 Angular2 的新手,不知道我做错了什么。在 Angular1 中,我只需使用 $scope 访问它们。

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    你需要使用this关键字:

    export class NavigationComponent {
      landing = false;
      portfolio = true;
    
      changeMiniNavLanding() {
        this.landing = true;
        this.portfolio = false;
      }
    
      changeMiniNavPortfoliofunction() {
        this.landing = false;
        this.portfolio = true;
      }
    }
    

    这是因为 landingportfolio 是类(属性)的一部分。方法也是一样。

    在与组件关联的模板中,您不需要this 关键字,因为Angular2 在评估表达式时会自动查看组件类的属性和方法。只有与组件关联的元素才能在表达式中使用...

    【讨论】:

      【解决方案2】:

      这应该做你想做的:

      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;
          }
      }
      

      【讨论】:

      • 一次landing 变量用false/true 值初始化(IDE 将其视为bool),所以无论如何IDE 都会为其提供工具.. 但声明的数据类型是good to have
      猜你喜欢
      • 2021-03-08
      • 2018-02-02
      • 2020-12-14
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      相关资源
      最近更新 更多