非常简单的ngmodel示例

时间:2018-05-17 10:12:21

标签: javascript angular

我有一个简单的表格

<form role="form" (submit)="login()">
  <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" />
  <button type="submit" id="btnLogin" class="btn btn-atp btn-block btn-large">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不应该自动更新这个值吗?

2 个答案:

答案 0 :(得分:1)

您必须使用[(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中的[(发出了two-way 数据绑定的信号。从理论上讲,您只能绑定到事件(ngModel)或值[ngModel]。但在这种情况下,您需要使用two-way 数据绑定[(ngModel)]

答案 1 :(得分:1)

您应该使用[(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)]