rook
rook

Reputation: 3008

Angular 2. Set value of ControlGroup in data driven form

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

Upvotes: 1

Views: 1630

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

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

Upvotes: 1

Related Questions