简体   繁体   English

非常简单的 ngModel 示例

[英]Very simple ngModel example

I have a simple form我有一个简单的表格

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

and a component ts.和一个组件 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;
  }
}

service服务

authenticate(credentials, callback) {
  console.log(credentials);
  const headers = new HttpHeaders(credentials ? {
   authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
  } : {});
}

My problem is that the credentials are always '' .我的问题是凭证总是'' Shouldn't the ngModel update these values automatically? ngModel不应该自动更新这些值吗?

You should use [(ngModel)] to set values like this -您应该使用[(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" />

As of now, you are using [ngmodel] which is just attribute binding to set value into your DOM and display it back.到目前为止,您正在使用[ngmodel] ,它只是属性绑定来将值设置到您的 DOM 中并将其显示回来。

But if you want to update value from view part you should use two way data binding [(ngModel)]但是如果你想从视图部分更新值,你应该使用两种方式数据绑定[(ngModel)]

You have to use [(ngModel)] instead of [ngModel]你必须使用[(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" />

because [( in Angular is signalling a two-way data binding . Theoretically you could only bind to an event (ngModel) or to a value [ngModel] . But in this case you need to use two-way data binding : [(ngModel)]因为[(在 Angular 中表示two-way数据绑定。理论上你只能绑定到事件(ngModel)或值[ngModel] 。但在这种情况下,你需要使用two-way数据绑定[(ngModel)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM