从angular2中的button元素调用时,router.navigate不起作用

时间:2016-04-26 04:40:46

标签: typescript angular angular2-routing

这是我的其中一个组成部分:

@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']);
    }
}

这是上述组件的模板:

<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>

如果从goToResetPassword()的{​​{1}}拨打goToRegister()(click),它就可以正常工作。

但是,它不起作用如果我将html元素更改为<a>,它只是重新加载整个应用程序而不会在控制台中抛出任何错误。

2 个答案:

答案 0 :(得分:1)

尝试这可能适合您: -

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

答案 1 :(得分:1)

这可能也有效

 (click)="goToResetPassword();false"

以防止按钮的默认提交行为。