Unable to get reactive forms working


#1

In component I’m doing this:

public loginForm: FormGroup = this.fb.group({
  email: ['', Validators.required],
  password: ['', Validators.required]
});

And then in template binding the form:

<StackLayout orientation="vertical" [formGroup]="loginForm">
  <TextField formControlName="email" hint="Email"></TextField>
  <TextField formControlName="password" hint="Password" secure="true"></TextField>
  <Button text="Log in" (tap)="login()"></Button>
</StackLayout>

But then when I log the loginForm value it’s still empty even if the text fields have values…

I’ve imported both ReactiveFormsModule and the NativeScriptFormsModule but doesn’t work. If I change password to any random name I don’t get an error or anything either. So it’s like it’s not even connected to the form in any way.

What am I doing wrong? I’m on nativescript cli 2.5+ which suggests this code should be working.


#2

Hello chrillewoodz,

I have used reactive forms with success in a current app we have.
To be honest I do not understand your issue.

Is it that is not showing errors? Or is it that the form shows valid?

Just as comment, in order to see errors from the validation errors, you should add code, to show certain labels, or icon or something if the field contains an error.
Which currently you are missing on your code.

This goes immediately after one of your text fields for example.
Something like:

<StackLayout class="error-container" *ngIf="!registerForm.get('password').valid && registerForm.get('password').dirty" >
	<Label *ngIf="registerForm.get('password').errors.required"  text="This field is required" ></Label>
	<Label *ngIf="!registerForm.get('password').hasError( 'maxlength' ) && !registerForm.get('password').errors.required"  text="This field is over max length" ></Label>
</StackLayout>

Hope this helps.