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?