2

我正在使用model driven forms并且正在寻找一种更好的方法来将数据绑定到相关的formControlName's,因为我的表单上有超过 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 
    })
  }
)

有没有办法“自动”做到这一点?

4

3 回答 3

8

你可以这样做:

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/

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

在您的订阅中,只需这样做:this.refferalForm.setValue(this.referringData); setValue 需要一个具有键/值对的对象

于 2017-02-22T12:05:31.327 回答
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

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

笔记:

虽然没有任何地方说你不能同时使用FormsModulewith ReactiveFormsModule,但我不会这样做,我更喜欢使用第一种方法。

于 2017-02-22T22:32:51.050 回答
-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: 'any@any.com'
 });
}
于 2019-03-17T13:13:52.943 回答