非常简单的ngModel示例

3
我有一个简单的表单。
<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不应该自动更新这些值吗?


顺便说一下,这是教程链接:https://spring.io/guides/tutorials/spring-security-and-angular-js/ - user9804931
2个回答

4

您应该使用 [(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中并将其显示回来。

但是,如果您想从视图部分更新值,则应使用双向数据绑定[(ngModel)]


你现在解决了吗? - Pardeep Jain

3

您需要使用[(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" />

因为在Angular中,[()]表示双向数据绑定。理论上,你可以只绑定到一个事件(ngModel)或者一个值[ngModel]。但是在这种情况下,你需要使用双向数据绑定:[(ngModel)]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接