Rohit Arya
Rohit Arya

Reputation: 6791

router.navigate doesn't work when called from button element in angular2

This is my one of the components:

@Component({
    selector: 'login-view',
    templateUrl: 'app/login/login.component.html',
    directives: [MATERIAL_DIRECTIVES, FORM_DIRECTIVES]
})
export class LoginComponent implements OnInit{

    loginForm: ControlGroup;

    constructor(
        private _formBuilder: FormBuilder, private _router: Router) {
    }

    ngOnInit() {
        // some stuffs
    }

    submitLoginForm(){
        // to be implemented
    }

    goToRegister(){
        this._router.navigate(['/Register']);
    }

    goToResetPassword(){
        this._router.navigate(['/ResetPassword']);
    }
}

This is the template for the above component:

<form [ngFormModel]="loginForm" (ngSubmit)="submitLoginForm()">

    <input md-input ngControl="mobileNumber" type="number" id="mobileNumber">

    <input md-input type="password" ngControl="password" id="password"/>

    <button md-raised-button type="submit" class="md-raised md-primary">Login</button>

    <div>
        // These Work
        <a md-button class="md-primary" (click)="goToResetPassword()">Forgot password?</a>
        <a md-button class="md-primary" (click)="goToRegister()">New here? Register</a>

       //These don't work, reloads the app
       <button md-button class="md-primary" (click)="goToResetPassword()">Forgot password?</button>
       <button md-button class="md-primary" (click)="goToRegister()">New here? Register</button>
    </div>
</form>

If am calling goToResetPassword() or goToRegister() from (click) of <a> it works as it is supposed to.

But, it doesn't work If I change the html element to <button>, it just reloads the whole app without throwing any error in the console.

Upvotes: 1

Views: 593

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

This might also work

 (click)="goToResetPassword();false"

to prevent the default submit behavior of the button.

Upvotes: 1

mayur
mayur

Reputation: 3618

Try this may work for you : -

   <a type="button" class="btn "              
   [routerLink]="['/Foo']">{{labels.CancelBtnText}}</a>

Upvotes: 1

Related Questions