1

why this code call twice the method 'addHero' ?

        @Component({
      selector: 'little-tour',
      template: `
        <input #newHero
          (keyup.enter)="addHero(newHero.value); newHero.value='' "
          (blur)="addHero(newHero.value); newHero.value='' ">
        <button (click)=addHero(newHero.value)>Add</button>
        <ul><li *ngFor="let hero of heroes">{{hero}}</li></ul>

        <p>{{pressed}}</p>
      `
    })
    export class LittleTourComponent {
        number = 1;
        pressed='';
      heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
      addHero(newHero: string) {
          if (newHero) {
            if (this.heroes.join('').indexOf(newHero) < 0) {
                this.heroes.push(newHero);
            }
            this.pressed+=' **(into IF)** ';
        }
        //newHero= " ";

        this.pressed+='pressed ' +this.number+', ';
        this.number++;
      }
    }

This is an example:

(into IF) pressed 1, pressed 2, (into IF) pressed 3, pressed 4

6
  • 1
    What is "into IF"? Commented Nov 28, 2016 at 12:42
  • It would be called twice when you do what exactly? Commented Nov 28, 2016 at 12:48
  • the addHero() is called twice because of (blur). Why do want to addHero ob blur? Commented Nov 28, 2016 at 12:56
  • It was an example on official documentation: angular.io/docs/ts/latest/guide/user-input.html Commented Nov 28, 2016 at 13:30
  • "into IF" is just string for debugging Commented Nov 28, 2016 at 13:31

2 Answers 2

2

You have three different ways on your code to call addHero:

  • On enter key pressed while input is focused
  • On input text blur (focus lost)
  • On button click

Probably what you see is caused by the fact that blur on input text is executed when you click on button. I'd say you should remove blur handler since it conflicts with button click.

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

Comments

0

use this , it should work fine

<input #newHero
          (keyup.enter)="test(newHero.value); newHero.value='' "
          (change)="test(newHero.value); newHero.value='' ">

Comments

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.