Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button is reloading my page even if he's not a submit

Tags:

angular

Alpha : 44

I have a problem currently with the button in angular2...

they seems to have strange behaviour that doesn't exist in angular1 and even in any pure html it doesn't do the strange behaviour

everytime i click on my button, the page is reloading... it's not a submit button.. so it shouldn't reload the page!

another behaviour that is pretty frustrating in angular2 that a lot of error make the browser to reload and we lose the console log...

here is the code

createPlayer() {
    let p = new PlayerModel('s', 1);
    console.log(p);
}

<form>
    <div class="form-group">
        <label for="name" class="control-label">
            Name:
        </label>

        <input type="text" id="name" class="form-control"/>
    </div>

    <div class="form-group">
        <label for="score" class="control-label">
            Score:
        </label>

        <input type="number" id="score" class="form-control"/>
    </div>

    <div class="form-group">
        <button (click)="createPlayer()" class="btn btn-default">
            Create a Player
        </button>
    </div>
</form>

there is no error while i do the process with debugger in first statement but when the end of the button happen it reload the page...

like image 968
Vincent Bilodeau Avatar asked Oct 23 '15 13:10

Vincent Bilodeau


2 Answers

Unless you specify otherwise, submitting a form is the default behavior of <button>s (I know, right?). You can avoid this by not having a containing form, by adding type="button", or by preventing the default behavior in createPlayer.

like image 163
Jacob Raihle Avatar answered Oct 26 '22 19:10

Jacob Raihle


For others who may be interested: create your form like this:

 <form (ngSubmit)="onSubmit()" #feedback="ngForm">

Then create an onSubmit() function in your component.

For an example go to angular.io and go to Basics/Forms on the left menu, scroll down and click the "Live Demo" link.

like image 20
Post Impatica Avatar answered Oct 26 '22 19:10

Post Impatica