Manually Set Value for FormBuilder Control

This is driving me nuts, I’m under the gun and can’t afford to spend another whole day on this.

I am trying to manually set a control value (‘dept’) within the component, and it’s just not working – even the new value logs to console properly.

Here is the FormBuilder Instance:

initForm() {
  this.form = this.fb.group({
    'name': ['', Validators.required],
    'dept': ['', Validators.required],
    'description': ['', Validators.required],
  });
}

This is the event handler that receives the selected dept:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!
 
  // This is how I am trying to set the value
  this.form.controls['dept'].value = selected.id;
}

Now when the form is submitted and I log out this.form the field is still blank! I’ve seen other ppl use updateValue() but this is beta.1 and I don’t see that as a valid method to call on the control.

I have also tried to call updateValueAndValidity() with no success :(.

I would just use ngControl="dept" on the form element, like I’m doing with the rest of the form but its a custom directive/component.

<ng-select
  [data]="dept"
  [multiple]="false"
  [items]="depts"
  (selected)="deptSelected($event)" <!-- This is how the value gets to me -->
  [placeholder]="'No Dept Selected'">
</ng-select>

11 Answers
11

Leave a Comment