javascript - 非常简单的 ngModel 示例

标签 javascript angular

我有一个简单的表单

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

相关文章:

javascript - 按钮在移动模式下不显示

Angular2 重定向路由不会更改浏览器 url

javascript - 仅将唯一的对象添加到数组中

Javascript原型(prototype)继承区别

javascript - Angular Material 未正确加载样式

angular - store.select subscribe 中的更改检测需要 markForCheck。为什么?

angular - 等待两个 Observable 完成

Angular 5 上传文件以及其他对象的属性

Javascript innerHTML 超出范围问题?

javascript - 在 mustache javascript 中使用参数调用函数