【问题标题】:How do I consume a local variable value in angular2?如何在 angular2 中使用局部变量值?
【发布时间】:2023-03-09 20:03:01
【问题描述】:

我有一个简单的函数,可以将值作为数字返回给我。这个值基本上一个todolist中有多少项是不完整的。

testFunction() {
    var a = 0;
    this.todos.forEach(function(elem, i) {
                    if(elem.status === true) {
                        a += 1;
                    }
                })
                console.log(a); // gives correct length
    }

现在我看到了

Total todo Items  Left <span>{{a}}</span> //Nothing coming here?

如何在模板中记录a 的值

【问题讨论】:

  • 使其成为组件的属性
  • 您需要将变量定义为函数外部的私有/公共,作为您的类成员。
  • 简而言之,将a 定义为不在var 内,而是定义为this.a = 0;
  • 我已经这样做了 @FrankModica export class SomeComponent implements OnInit { todos : Todo[];一:任何;还有一个:数字
  • 所以你不需要在方法中定义你的a。删除 var a = 0; 代替 this.a = 0 并在循环内部使用 this.a += 1

标签: javascript angular


【解决方案1】:

Angular 只能使用组件自己的数据字段将数据绑定到模板。所以你的代码需要如下

testFunction() {
    this.a = 0;
    this.todos.forEach(function(elem, i) {
        if(elem.status === true) {
            this.a += 1;
        }
    }.bind(this))
    console.log(a); // gives correct length
}

UPD如果你想使用 ES6 语法,你甚至不需要绑定this,你可以使用一个箭头函数从父作用域传递this

testFunction() {
    this.a = 0;
    this.todos.forEach((elem, i) => {
        if(elem.status === true) {
            this.a += 1;
        }
    })
    console.log(a); // gives correct length
}

【讨论】:

  • 为什么要绑定先生?我错过了我认为的那部分。
  • @Mike 绑定用于在函数内部保留 this 的值,如果没有,则使用箭头函数link
  • 如果你想使用 ES6 语法,你就写for (const elem of this.todos) { … }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多