我是Angular2的新手,并试图理解为什么我的页面会被刷新,然后尝试从表单数据中设置一些属性。
以下是组件:
import { Component } from '@angular/core';
import { Credentials } from './authentication/Credentials';
import { User } from './authentication/User';
@Component({
selector: 'loginForm',
templateUrl: 'app/shared/loginForm.component.html'
})
export class LoginForm {
//user: User;
credentials: Credentials;
submitForm(form: any): void {
this.credentials.username = form.username;
this.credentials.password = form.password;
console.log(form.username);
}
}
如果我注释掉this.credentials.username
和this.credentials.password
行,则会将提交的用户名记录到控制台。只要这些行被取消注释(如上所述),页面就会完全重新渲染(刷新)。
修改
我真正想要做的是能够在没有刷新的情况下对用户进行身份验证。这也是模板:
<form #form="ngForm" class="navbar-form navbar-right" (ngSubmit)="submitForm(form.value)">
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" ngModel required>
<input type="password" class="form-control" placeholder="Password" name="password" ngModel required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log in</button>
</div>
</form>
答案 0 :(得分:3)
请通过将submitForm()绑定到按钮事件...
来检查它<button type="submit" class="btn btn-default" (click)="submitForm()">Log in</button>
同时从表单中删除ngSubmit