user203687
user203687

Reputation: 7237

component function gets executed twice in angular 2

I have a component as follows:

    import { Component, OnInit } from '@angular/core';

    @Component({
        selector: 'app',
        template: `
<div>
    <div>value of a :
        <input [(ngModel)]="a" />
    </div>
    <div>value of b :
        <input [(ngModel)]="b" />
    </div>
    <div>
        Value of a = {{a}}
        <br> Value of b = {{b}}
        <br> Sum instantaneous {{calc(a+b)}}
    </div>
</div>
`   
    })
    export class AppComponent implements OnInit {

        a: string = "";
        b: string = "";
        constructor() { }

        ngOnInit() {
        }

        calc() {
            console.log('test');
            return (+this.a + +this.b);
        }
    }

Every time, I modify (say, key press) anything in textboxes or even just focusing/defocusing textboxes, the 'calc' function gets executed twice.

What am I missing here or how can I get the function execute once (instead of twice).

Upvotes: 2

Views: 476

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19754

It's happening because change detection is run more often than you probably think, especially since you're in developer mode and everything gets checked twice.

You're not supposed to call functions from the template for exactly this reason. One of the solutions is to use pipes which can be declared as pure functions.

@Pipe({name: 'calc'})
export class CalcPipe implements PipeTransform {
  public transform(a: number, b: number): number {
    return a + b
  }
}

And then use it like this.

{{ a | calc : b }}

Otherwise, you might want to write custom logic that will update a property in your class. Then just bind the property instead of the function call.

Upvotes: 1

Related Questions