Reputation: 963
[As a Newbie tried to put this into plnkr, but couldn't; problems getting @angular/forms added to json.]
Purpose: to iron out things I need to know to do all my work in FormBuilder HTML:
<input type="text"
formControlName="bucket"
value="A"
[(ngModel)]="AllData.bucket" />
// added to button to test: [disabled]="this.myTestForm.invalid || this.myTestForm.pristine"
<div><button
type="submit">submit</button></div>
</form>
<div *ngIf="result.length > 0 ">{{result}}</div>
<div *ngIf="myTestForm.errors === true ">ERRORS FOUND</div>
Running the app: shows the formbuilder in the ts below initializes the input field correctly and if I add the [disabled] expression commented above it disables button correctly.
Here's the ts: import {Component, OnInit} from '@angular/core'; import {Validators, FormBuilder, FormGroup} from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
myTestForm: FormGroup;
result: string;
AllData = { //// wired to ngModel
bucket: '12'
}
constructor(private fb: FormBuilder) {
this.result = '';
}
ngOnInit() {
this.myTestForm = this.fb.group({
bucket: ['starting value', [Validators.required, Validators.minLength(5)]]
<-- ngModel bucket above overrides this init value as expected -->
});
}
onSubmit(value: any) { // ways to show results
this.result = this.AllData.bucket;
// OR //
this.result = this.myTestForm.controls['bucket'].value;
// OR //
this.result = this.myTestForm.get('bucket').value;
}
}
The app inits with '12' in the input field as expected. No matter what I put into the textbox before pressing the submit button, devTools always shows the myTestForm 'error' property as undefined.
I'm expected errors to have some sort of string(s) based on the type of error(s) that is occurring.
Further, I scoured the web for ways to capture invalid fields as soon as the error occurs (of course for !pristine fields), but I couldn't get anything to work.
Any help will be much appreciated.
Thanks in advance, Chuck
Upvotes: 1
Views: 3977
Reputation: 29705
I have created a small demo to provide a suggestion on your approach
Do not use [(ngModel)]
when your are using reactive forms approach, as ngModel
will take precedence over the formControl
and set its value to the control irrespective of formcontrol's
value, that you have initialized.
<form [formGroup]="myTestForm" >
<input type="text"
formControlName="bucket"
value="A" />
<div><button
[disabled]="myTestForm.invalid || myTestForm.pristine"
type="submit" >submit</button></div>
</form>
To check form errors, use hasError()
on controls
<div *ngIf="myTestForm.get('bucket').hasError('required')">Input is required</div>
<div *ngIf="myTestForm.get('bucket').hasError('minlength')">Min length should be 5</div>
Upvotes: 3