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

问题描述 投票:2回答:3

我正在使用model driven forms,我正在寻找一种更好的方法将数据绑定到与formControlName相关的,因为我的表单上有超过25个字段,我不想为所有字段编写代码,因为我已经写了对于下面。

模板:

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

零件:

this.refferalService.getReferringDataEdit(id).subscribe(
  result => {
    this.referringData = result.responseObject;
    this.refferalForm.patchValue({ 
      firstName: this.referringData.firstName 
    })
  }
)

有没有办法“自动”?

angular angular2-template angular2-forms angular2-formbuilder
3个回答
7
投票

你可以这样做:

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>

并将其与(ngSubmit)绑定。因此,每当您点击提交时,该值将反映在myForm.value中。 myForm会将表单存储为键/值对。

在控制台中,您的输出将是:

Object : 
firstName:....
lastName: ...

你可以参考:http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

EDIt:由于要求是从服务中保存数据:

在你的订阅中只需这样:this.refferalForm.setValue(this.referringData); setValue期望一个具有键/值对的对象


6
投票

我可以看到两种方法:

第一种方法:

您可以为“表单”(新建/编辑)创建一般方法,并使用或不使用值创建表单,这样:

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]]
  });
}

DEMO

第二种方法:

在这种方法中,您可以使用[(ngModel)]自动绑定它,因此您无需在组件文件中执行任何操作。

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

  // init the form as always
}

并在模板中使用[(ngModel)]来绑定值:

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

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

DEMO

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

注意:

虽然没有任何地方说你不能同时使用FormsModuleReactiveFormsModule,但我不会这样做,我宁愿使用第一种方法。


-1
投票

要绑定动态值或替换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: '[email protected]'
 });
}
© www.soinside.com 2019 - 2024. All rights reserved.