skip to Main Content

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


  1. 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

    <input type="radio" [(ngModel)]="option" name="option" value="Pool">
    <input type="radio" [(ngModel)]="option" name="option" value="Laundry">
    <div *ngIf="error">{{error}}</div><!-- Displays error -->
    

    Typescript Page

    import { Component } from '@angular/core';
    import { CommonModule, Location } from '@angular/common';
    
    import { FormGroup, FormBuilder,FormControl, Validators, FormArray } from '@angular/forms';
    
    
    export class HotelComponent {
    //
      option?: string;
      form: FormGroup;
      error?: string;
    
      constructor(private fb: FormBuilder) {
    
    
        this.form = this.fb.group({
          option: ['', Validators.required],
        });
      }
    
      onSubmit() {
        if(!option) {
           //if option value is undefined (not selected)
           error = "Choose an option";
           console.log(error);
           return;
        }
        if (this.form.valid) {
            console.log(option);
    
              
        }
      }
    }
    
    Login or Signup to reply.
  2. 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:

    <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>
    

    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:

     this.form = this.fb.group({
          option: ['', Validators.required],
        });
     this.form.controls['option'].markAsTouched();
    

    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"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search