Ionic3 FormBuilder绑定模型值

时间:2018-04-18 08:55:23

标签: angular ionic-framework ionic2 ionic3

我有一个模特:

export class ProfileModel {

  constructor(
    public name: string,
    public age: number,
    ...
    ...
    ){}

}

我已经构建了一个表单来更新值:

<form  [formGroup]="profileForm" (ngSubmit)="updateProfile(profileForm.value)" autocomplete="off">

        <!-- Name -->
        <ion-item>
            <ion-label>My name</ion-label>
            <ion-input formControlName="name"></ion-input>
        </ion-item>

        <!-- Age -->    
        <ion-item>
            <ion-label>Age*</ion-label>
            <ion-input type="number" formControlName="age"></ion-input>
        </ion-item>


    ...
    ...

    <button ion-button full type="submit" [disabled]="!profileForm.valid">Update</button>
</form>

在我的组件中:

export class ProfilePage {

    public profileForm : FormGroup;

  public receievedProfileData: ProfileModel; 

  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams, 
    private formBuilder: FormBuilder,
    private userService: UserService) {

    this.receievedProfileData= new ProfileModel(null, null,null,null,null,null,null,null,null,null,null,null,null,null);

    this.profileForm = this.formBuilder.group({
      name: [''],
      age: ['', Validators.required],
      ...
      ...
    });

  }



  ionViewWillEnter(){

    this.userService.getProfile().subscribe(
        data => {
          this.receievedProfileData.name=data.name;
          console.log(this.receievedProfileData)
        },
        error => {

        });

  }

  ionViewDidLoad() {


  }

  updateProfile(formData){

    this.userService.updateProfile(formData
      ).subscribe(
      data => {
        this.profileUpdateSuccessMessage="Profile updated successfully!";
      },
      error => {
        console.log("Profile update Error in Profile Page ", error);
      });
    }

  }

现在我看到所有字段都空白的表单。我想要做的是我的用户上次保存的任何值应该显示在表单上,​​即我必须以某种方式绑定它们。

我从后端获取当前配置文件信息并将其分配给 receievedProfileData 。如何进一步将其绑定到表单或模板?

1 个答案:

答案 0 :(得分:1)

从后端接收数据后,您需要执行patchValuesetValue {/ 1}}。

FormGroup

<强>的setValue

  

此方法执行严格检查,因此如果您尝试设置不存在的控件的值或者排除控件的值,则会抛出错误。

<强> patchValue

  

它接受组的超集和子集而不会抛出错误。

因此,如果您的数据对象完全镜像了表单对象,请使用ionViewWillEnter() { this.userService.getProfile().subscribe( data => this.profileForm.setValue(data) // data => this.profileForm.patchValue(data) ); } 。 否则,您必须使用setValue,或者在调用patchValue方法之前将数据对象转换为镜像表单对象。