1

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?

1
  • can u create a plunker? Commented Mar 4, 2017 at 9:33

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.