我有一个简单的表单
<form role="form" (submit)="login()">
<input type="text" name="username" id="username" required="required" [ngModel]="credentials.username"/>
<input type="password" name="password" id="password" required="required" [ngModel]="credentials.password" />
<button type="submit">Sign in</button>
</div>
</form>
和一个组件 ts。
export class LoginComponent implements OnInit {
credentials = {username: '', password: ''};
constructor(private loginService: LoginService, private http: HttpClient, private router: Router) { }
ngOnInit() { }
login() {
console.log(this.credentials);
this.loginService.authenticate(this.credentials, () => {
this.router.navigateByUrl('/');
});
return false;
}
}
服务
authenticate(credentials, callback) {
console.log(credentials);
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
}
我的问题是凭据始终是 ''
。 ngModel
不应该自动更新这些值吗?
最佳答案
您应该使用 [(ngModel)]
来设置这样的值 -
<input type="text" name="username" id="username" placeholder="Username" required="required" [(ngModel)]="credentials.username"/>
<input type="password" name="password" id="password" placeholder="Password" required="required" [(ngModel)]="credentials.password" />
截至目前,您使用的是 [ngmodel]
,它只是将值设置到 DOM 中并显示回来的属性绑定(bind)。
但是如果你想从 View 部分更新值,你应该使用两种方式的数据绑定(bind) [(ngModel)]
关于javascript - 非常简单的 ngModel 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50388866/