This is my form in angular.
hotel.component.html:
<div class="container-sm">
<div class="bg-light jumbotron text-center">
<h2>Hotel</h2>
</div>
<form [formGroup]="form" (submit)="onSubmit()" class="mb-3">
<div class="col">
<label class="form-label fw-bold">Ammenities:</label>
<div class="d-flex">
<div class="form-check me-4">
<label class="form-check-label"><input class="form-check-input" type="radio" name="option" value="Pool" formControlName="option"> Pool </label>
</div>
<div class="form-check">
<label class="form-check-label"><input class="form-check-input" type="radio" name="option" value="Laundry" formControlName="option"> Laundry </label>
</div>
</div>
<div *ngIf="form.controls['option'].touched && form.controls['option'].invalid">
<div *ngIf="form.controls['option'].hasError('required')" class="error">Please select an option</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="btn-group">
<button type="submit" class="btn btn-primary mr-1">Submit</button>
</div>
</div>
</div>
</form>
</div>
<br>
<br>
hotel.component.ts:
import { Component } from '@angular/core';
import { CommonModule, Location } from '@angular/common';
import { FormGroup, FormBuilder,FormControl, Validators, FormArray } from '@angular/forms';
export class HotelComponent {
//
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
option: ['', Validators.required],
});
}
onSubmit() {
if (this.form.valid) {
console.log(option);
}
}
}
Just a simple form with a radio and a submit button. If user tries to submit the form without selecting any options, the error message should be shown. Right now ,no error message appears when I click on submit without selecting ana option.
Can someone tell me how to make the validation work?
2
Answers
I don’t know much about FormBuilder, Formgroup, … but using Two-way binding is easier to understand
You can replace the Input radio elements in your HTML page with these
Typescript Page
You have added a condition that if your control is touched and invalid then only show the error. Talking about this condition which needs to be fixed:
To fix this issue either you can mark your control touched or remove touched condition from your HTML code.
form.controls['option'].touched
Component side to mark control tocuhed:
Moreover if you want to disable button if none of the options are selected then you can use this contion on button:
[disabled]="form.invalid"