Angular 角度2-如何自动将对象值绑定到与表单控件相关的对象?

Angular 角度2-如何自动将对象值绑定到与表单控件相关的对象?,angular,angular2-template,angular2-forms,angular2-formbuilder,Angular,Angular2 Template,Angular2 Forms,Angular2 Formbuilder,我正在使用模型驱动表单,我正在寻找一种更好的方法将数据绑定到与formControlName相关的表单,因为我的表单上有超过25个字段,我不想像我在下面写的那样为所有字段编写代码 模板: <input type="text" class="form-control" formControlName="firstName" name="firstName" placeholder="First Name" required

我正在使用
模型驱动表单
,我正在寻找一种更好的方法将数据绑定到与
formControlName
相关的表单,因为我的表单上有超过25个字段,我不想像我在下面写的那样为所有字段编写代码

模板:

<input type="text"
       class="form-control"
       formControlName="firstName"
       name="firstName"
       placeholder="First Name"
       required>

有没有“自动”完成的方法?

您可以这样做:

import {FormGroup,FormBuilder,FormControl} from '@angular/forms';

export class formComponent{
  myForm : FromGroup
  constructor(fb: FormBuilder){
    this.myForm= fb.group({
        'firstName' : [''],
        'lastName' : [''],
    });
 }
 onSubmit(value:string){
   console.log(form);
 }
}
稍后在HTML中使用它,如:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<input type="text" placeholder="FirstName" [formControl] = "myForm.controls['firstName']">

<input type="text" placeholder="LastName" [formControl] = "myForm.controls['lastName']">
<button type="submit">Submit</button>
</form>
你可以参考:

编辑:由于要求保存服务中的数据:


在订阅中,只需执行以下操作:
this.refferalForm.setValue(this.referringData)设置值需要具有键/值对的对象

我可以看到两种方法:

第一种方法:

<input type="text"
       class="form-control"
       formControlName="firstName"
       name="firstName"
       placeholder="First Name"
       required>
您可以为两个“表单”(新建/编辑)创建通用方法,并通过以下方式创建包含或不包含值的表单:

ngOnInit() {
  // Imagine that the data is coming from API:
  const referringData = { firstName: 'First', lastName: 'Last' };
  this.initForm(referringData);
}

private initForm(data = {}): void {
  // Note that you can pass nothing to this function, 
  // so the values will be initially undefined (no problem with that)

  this.myForm = this.formBuilder.group({
    firstName: [data.firstName, [Validators.required]],
    lastName: [data.lastName, [Validators.required]]
  });
}

第二种方法:

<input type="text"
       class="form-control"
       formControlName="firstName"
       name="firstName"
       placeholder="First Name"
       required>
在这种方法中,您可以使用
[(ngModel)]
自动绑定它,因此您不需要在组件文件中执行任何操作

ngOnInit() {
  // Imagine that the data is coming from API:
  this.referringData = { firstName: 'First', lastName: 'Last'};

  // init the form as always
}
并在模板中使用[(ngModel)]绑定

this.refferalService.getReferringDataEdit(id).subscribe(
  result => {
    this.referringData = result.responseObject;
    this.refferalForm.patchValue({ 
      firstName: this.referringData.firstName 
    })
  }
)
<input type="text" formControlName="firstName" [(ngModel)]="referringData.firstName">

<input type="text" formControlName="lastName" [(ngModel)]="referringData.lastName">

检查以上两种方法的完整来源

注意:

HTML Code :

 <mat-form-field appearance="outline">
                <mat-label>Email</mat-label>
                <input matInput formControlName="email"  >
                <mat-icon matSuffix class="secondary- 
                text">mail</mat-icon>

 </mat-form-field>    

Component Code :

ngOnInit () {
/** This create form group */
 this.resetPasswordForm = 
    this._formBuilder.group({
        email:new FormControl({ value: '', disabled:true }),
    });
    this.updateEmail()
}

updateEmail(){
    /** Update value of formControl */
     this.resetPasswordForm.patchValue({
            email: 'any@any.com'
 });
}

虽然没有任何地方说您不能将
FormsModule
ReactiveFormsModule
一起使用,但我不同意这一点,我宁愿使用第一种方法。

要绑定动态值或替换fromControl的值,我们可以使用patchValue方法。

HTML Code :

 <mat-form-field appearance="outline">
                <mat-label>Email</mat-label>
                <input matInput formControlName="email"  >
                <mat-icon matSuffix class="secondary- 
                text">mail</mat-icon>

 </mat-form-field>    

Component Code :

ngOnInit () {
/** This create form group */
 this.resetPasswordForm = 
    this._formBuilder.group({
        email:new FormControl({ value: '', disabled:true }),
    });
    this.updateEmail()
}

updateEmail(){
    /** Update value of formControl */
     this.resetPasswordForm.patchValue({
            email: 'any@any.com'
 });
}
HTML代码:
电子邮件
邮件
组件代码:
恩戈尼尼特(){
/**这将创建表单组*/
this.resetPasswordForm=
这是.\u formBuilder.group({
电子邮件:new FormControl({value:'',disabled:true}),
});
this.updateEmail()
}
更新邮件(){
/**更新formControl的值*/
此参数为.resetPasswordForm.patchValue({
电邮:'any@any.com'
});
}

Hi我已经做了这些事情来保存数据。我想知道如何将数据绑定到相对formcontrol以进行编辑/更新。在订阅中,只需执行以下操作:this.refferalForm.setValue(this.referringData);setValue需要具有键/值对的对象。我正在使用ngx mydatepicker进行日期选择,我在上面使用了this.refferalForm.patchValue(this.referringData)来绑定数据,但它不会绑定日期。你知道如何绑定日期吗?