mario595
mario595

Reputation: 3761

Form doesn't trigger validation if setting input value programatically

I have a form like this in Angular2:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input type="text" id="name" formControlName="name" value="{{elementToEdit?.name}}">
  <button type="submit" [disabled]="!form.valid">Save</button>
</form>

And the component code looks like:

export class ElementEditComponent implements OnInit {
  form: FormGroup;
  elementToEdit: Element;

  constructor(fb: FormBuilder,
          private elementService: ElementService) {
          this.form = fb.group({
              "name": new FormControl("", Validators.required)
          });
  }

  ngOnInit() {
    this.route.params
    .switchMap((params: Params) => this.recipeService.getElement(+params['id']))
    .subscribe(element => this.elementToEdit = element);
  }
}

I am doing it this way because I have the same form for editing existing elements and to create new elements, to if in the ngOnInit I try to get the element from the service in case I am receiving an id in the parameters. If so, when I receive the element, I set it to elementToEdit.

This works fine so far and the input takes the value as soon as the element is received. The problem I have is that when that happens, the validation of the form doesn't get triggered, so the button appears disabled even when the input is not empty.

Does anyone knows how can I solve this so the validation of the form gets triggered when the input's value is changed?

Upvotes: 1

Views: 2272

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122105

With the reactive forms you don't bind the value into the template directly, that's what the formControlName is for. Instead you update the FormGroup instance and let Angular update the displayed value, validation status, etc.:

ngOnInit() {
  this.route.params
    .switchMap((params: Params) => this.recipeService.getElement(+params['id']))
    .subscribe(element => this.form.patchValue(element);
}

I'd recommend running through the docs: https://angular.io/docs/ts/latest/guide/reactive-forms.html

Upvotes: 2

Related Questions