角度插值多次调用该方法

时间:2017-12-22 15:08:05

标签: angular angular4-forms

在Angular 4中,

app.component.html

<div>Counter: {{GetCount()}}</div>

app.component.ts

    import { Component, OnInit } from '@angular/core';
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
        export class AppComponent  implements OnInit {
    constructor() {

      }

     ngOnInit()
     {

     }
   counter:number = 1;

  GetCount(): any {

    this.counter++;
    return this.counter;

  }
}

我的输出显示在屏幕上:

专柜:4

怎么可能?我在我的html中只调用一次GetCount方法,当我在方法中设置断点时,它会打4次。 我在这里做错了什么。

3 个答案:

答案 0 :(得分:2)

没错。 Angular会多次调用您的表达式,以检查值是否已更改。

答案 1 :(得分:2)

当您从html中调用类似的方法时,此方法将调用每个角度变化检测周期。

如果您只想调用此方法一次,我建议您从try: # Adding field 'Bug.bize_size_tag_name' db.add_column('search_bug', 'bize_size_tag_name', orm['search.bug:bize_size_tag_name']) except MySQLdb.OperationalError, errorCode: if errorCode[0] == 1060: pass else: raise

调用它
ngOnInit

在html中打印couter变量

ngOnInit(){
      GetCount()
}
 counter:number = 1;

 GetCount(): void{    
   this.counter++;     
 }

答案 2 :(得分:2)

Angular会在每次检查更改时评估该表达式,该更改与DoCheck生命周期钩子相关联。