I am trying to create simple contact form, nothig fancy. As it is said in title instead of value from label there is strange output of Validators code. Not sure why is that, I am using labels and placeholders and event with that inputs are not overridden. Everything works fine when I will remove Validators from Form Controls.
export class BookComponent implements OnInit {
contactForm: FormGroup;
requestTypes = ['Services', 'Other']
constructor() {
this.contactForm = this.createFormGroup();
}
ngOnInit() {
}
createFormGroup() {
return new FormGroup({
fullName: new FormControl([
Validators.required,
Validators.pattern("^([a-zA-Z'-.]+ [a-zA-Z'-.]+)$")]),
email: new FormControl([
Validators.required]),
serviceType: new FormControl([
Validators.required])
})
}
onSubmit() {
const result = this.contactForm.value;
console.log(result)
}
}
<form class="form" [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<div class="form__group">
<input
type="text"
id="name"
class="form__input"
placeholder="Full Name"
required
formControlName="fullName"
/>
<label for="name" class="form__label">Full Name</label>
</div>
<div class="form__group">
<input
type="email"
id="email"
class="form__input"
placeholder="Email"
required
formControlName="email"
/>
<label for="email" class="form__label">Email</label>
</div>
<div class="form__group u-margin-bottom-medium">
<div class="form__radio-group" *ngFor="let reqType of requestTypes">
<input
type="radio"
class="form__radio-input"
id="small"
formControlName="serviceType"
/>
<label for="small" class="form__radio-label">
<span class="form__radio-button"></span>
{{ reqType }}</label
>
</div>
</div>
<div class="form__group">
<button
type="submit"
class="btn btn--green"
[disabled]="contactForm.pristine"
>
Send request
</button>
</div>
</form>
Why is that? Everything works fine when I remove Validators from FormControls. This is how it looks like:
Any hints on this? Thank you in advance.
The is can be fixed by trying something like this.
fullName: new FormControl('',[
Validators.required,
Validators.pattern("^([a-zA-Z'-.]+ [a-zA-Z'-.]+)$")]),
In new FormControl the first parameter is taken as value, not as a validator, so you will be getting that issue. In case of dropdown you can try like this.
fullName: new FormControl([],[
Validators.required,
Validators.pattern("^([a-zA-Z'-.]+ [a-zA-Z'-.]+)$")]),