1

Let's say I have this model:

export class MyModel {
    constructor(
        public id: number,
        public name: string
    ) {}
}

and this ControlGroup:

export class MyComponent {
    form: ControlGroup;
    model: MyModel;

    constructor(builder: FormBuilder) {
        this.form = this.builder({
            'id' : [''],
            'name' : ['']
        })
    }
}

To get form's data I can simply do that (if field names match):

this.model = this.form.value;

But how can I set form's value in the same manner?

something like: this.form.value = model;

Getting the following error: Cannot set property value of #<AbstractControl> which has only a getter

Thank you!

UPD: Based on Günter Zöchbauer's suggestion below I ended up with that helper method:

setFormValues(form: ControlGroup, model: any) {

    for(var key in model) {
        var ctrl = (<Control>form.controls[key]);
        if ( ctrl != undefined )
            ctrl.updateValue(model[key]);
    }
}
rook
  • 2,819
  • 4
  • 25
  • 41

1 Answers1

1

The ControlGroup returned from this.builder.group(...) doesn't support to set the value. To set the value you have to set it on each control individually like:

  setValue() {
    let value = {id: 'xxx', name: 'yyy'};
    Object.keys(value).forEach((k) => {
      this.form.controls[k].updateValue(value[k]);
    });
  }

Plunker example

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you. Had to make some mods but finally it worked. Not marking this as accepted answer because it's a workaround. Hopefully they will implement such functionality in future releases and someone will mention it here. But I upvoted your comment. – rook Apr 23 '16 at 20:13