简体   繁体   English

如何从 FormGroup 获取值输入表单

[英]How to get value input form from FormGroup

Good day, guys I'd like to find the solution to solve my problem.美好的一天,伙计们,我想找到解决我问题的方法。 I have a FormGroup like this :我有一个这样的FormGroup

  profileForm  = new FormGroup({ 
    username   : new FormControl(),
    firstname  : new FormControl(),
    lastname   : new FormControl(),
    email      : new FormControl(),
    password   : new FormControl(),
  }); 

And I'd like to get the value by using :我想通过使用获得价值:

const user = {
  firstname : this.profileForm.get('firstname').value,
  lastname  : this.profileForm.get('lastname').value,
  username  : this.profileForm.get('username').value,
  email     : this.profileForm.get('email').value,
  password  : this.profileForm.get('password').value
}
console.log(user)

But I got null value for each input form.但是每个输入表单我都得到了空值。 But the value exists in the HTML form input :但该值存在于 HTML 表单输入中:

<input name="username" matInput placeholder="Username" formControlName="username" [readonly]="true" value="{{details?.data.username}}" >

Help me to fix this, thank you.帮我解决这个问题,谢谢。

Your mistake is that you access the Formgroup (which is basically an object which contains all formControls), which don't contain the value.您的错误是您访问了不包含值的 Formgroup(它基本上是一个包含所有 formControl 的对象)。 You should be access controls of the Form group.您应该是 Form 组的访问控制者。 An example:一个例子:

this.profileForm.controls.username.value

I think value="{{details?.data.username}}" is not binding value back to you.我认为value="{{details?.data.username}}"并没有绑定价值给你。 It just prints the value in dom.它只是打印 dom 中的值。

I assume you getting data details?.data.username in ngOnInit() ( or may be somewhere else) from there you can bind to your form like this我假设您在ngOnInit() (或可能在其他地方)中获取数据details?.data.username从那里您可以像这样绑定到您的表单

this.profileForm.get('firstname').setValue(details?.data.username)

and remove this value="{{details?.data.username}}" from html.并从 html 中删除此value="{{details?.data.username}}"

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

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