简体   繁体   English

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

[英]Angular 2 - How to automatically bind object values to related to Form Controls?

I'm using model driven forms and I'm searching a better way to bind the data to related to formControlName 's because I have more than 25 fields on my form and I don't want to have to write that code for all fields as I have written for below. 我正在使用model driven forms ,我正在搜索更好的方法将数据绑定到与formControlName相关的因为我的表单上有超过25个字段,我不想为所有字段编写该代码正如我在下面写的那样。

Template: 模板:

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

Component : 组件

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

Is there a way to do it "automatically"? 有没有办法“自动”?

You can do it Like this : 你可以这样做:

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

Later in your HTML use it like : 稍后在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>

and bind it with (ngSubmit) . 并将其与(ngSubmit)绑定。 So whenever you hit the submit , the value will be reflected in myForm.value . 因此,每当您点击提交时,该值将反映在myForm.value中。 myForm will store the form as key/value pairs. myForm会将表单存储为键/值对。

In the console , your output will be : 在控制台中,您的输出将是:

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

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

EDIt: Since the requirement was to save the data from the service: EDIt:由于要求是从服务中保存数据:

In your subscribe just do like this : this.refferalForm.setValue(this.referringData); 在你的订阅中,只需这样: this.refferalForm.setValue(this.referringData); setValue expects an object with key/value Pairs setValue期望一个具有键/值Pairs的对象

I can see two ways to do this: 我可以看到两种方法:

First approach: 第一种方法:

You could create a general method for both "forms" (new/edit) and create the form with or without the values, this way: 您可以为“表单”(新建/编辑)创建一般方法,并使用或不使用值创建表单,这样:

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 DEMO

Second approach: 第二种方法:

In this approach you can bind it automatically with [(ngModel)] , so you don't need to do nothing in your component file. 在这种方法中,您可以使用[(ngModel)]自动绑定它,因此您不需要在组件文件中执行任何操作。

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

  // init the form as always
}

And in template use [(ngModel)] to bind the values : 并在模板中使用[(ngModel)]来绑定

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

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

DEMO DEMO

Check the full sources for both approaches above. 检查上述两种方法的完整来源。

Note: 注意:

Although there's nothing anywhere saying that you can't use both FormsModule with ReactiveFormsModule , I'd not go with this, I'd prefer to use the first approach. 虽然没有任何地方说你不能同时使用FormsModuleReactiveFormsModule ,但我不FormsModule ,我宁愿使用第一种方法。

To bind dynamic value or replacing value of fromControl, we can use patchValue method. 要绑定动态值或替换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'
 });
}

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

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