gpt4 book ai didi

javascript - 非常简单的 ngModel 示例

转载 作者:行者123 更新时间:2023-11-30 11:19:19 25 4
gpt4 key购买 nike

我有一个简单的表单

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com