angularangularjsangular-ui-router

How to make a drop down textbox required if the radio button is Yes?


I'm trying to code my program where I can have the dropdown textbox required if the answer to my radio button is yes. Right now I just have them both required. Is there a way I can read my value in the if statement I have for the state to solve this? The unemployed value for this part.

Right now they are both required.

<div class="container tb-10">
<form [formGroup]="form" (submit)="route()">
    <div>
        <div class="row">
            <h4>Unemployment:</h4>
            <div class="form-group">
                <label>Are you an individual who is or was in a period of unemployment that is at least 27 consecutive weeks and for all or part of that period you received unemployment compensation?</label>
                <div>
                    <label>
                        <input type="radio" name="unemployed" value="Y" formControlName="unemployed" > Yes&nbsp;&nbsp;
                    </label><br>

                    <label>
                        <input type="radio" name="unemployed" value="N" formControlName="unemployed" > No&nbsp;&nbsp;
                    </label><br>
                    <label *ngIf="hasError('unemployed', 'required') && isSubmitted">Please click on one of the option buttons above before submitting form!</label>
                </div>
                <div>
                    <label for="state" class="form-label">State:</label>
                    <select class="form-select" aria-label="State" id="state" value=""  formControlName="state" (focus)="controlFocussed()">
                        <option selected value=" ">Select State...</option>
                        <option value="1">One</option>
                        <option value="2">Two</option>
                        <option value="3">Three</option>
                    </select>
                    <label *ngIf="hasError('state', 'required') && isSubmitted">State is required.</label>
                </div>
            </div>
        </div>
    </div>
    <footer>
        <button id="exit" class="btn btn-danger pull-left" >Exit</button>
        <button id="submitform" type="submit" class="btn btn-primary" > Next</button>
    </footer>
</form>

component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';
import { NgModel } from '@angular/forms';
import {
Validators,
FormGroup,
FormBuilder,
FormsModule,
ReactiveFormsModule,
FormGroupDirective,
} from '@angular/forms';

@Component({
selector: 'app-unemployed',
templateUrl: './unemployed.component.html',
styleUrls: ['./unemployed.component.css']
})
export class UnemployedComponent {

  // add the following class property (needed to show the error message)
  isSubmitted = false;
  form!: FormGroup;


  constructor(private builder: FormBuilder,private router: Router) {
     this.initializeForm();
  }

 initializeForm() {
   this.form = this.builder.group({
     unemployed:  ['', Validators.required],
     state: ['', Validators.required],
   });
 }

 controlFocussed() {
   this.isSubmitted = false;
 }

 public hasError = (controlName: string, errorName: string) => {
   return this.form.controls[controlName].hasError(errorName);
 };



 route() {
   this.isSubmitted = true;
   if (!this.form.invalid) {
     this.router.navigateByUrl("/felony");
   }
 }
}

Solution

  • you just need to change the method of route()

    component.ts

        import { Component } from '@angular/core';
        import { Router } from '@angular/router';
        import { NgForm } from '@angular/forms';
        import { NgModel } from '@angular/forms';
        import {
        Validators,
        FormGroup,
        FormBuilder,
        FormsModule,
        ReactiveFormsModule,
        FormGroupDirective,
        } from '@angular/forms';
        
        @Component({
        selector: 'app-unemployed',
        templateUrl: './unemployed.component.html',
        styleUrls: ['./unemployed.component.css']
        })
        export class UnemployedComponent {
        
           isSubmitted = false;
           form!: FormGroup;
        
        
           constructor(private builder: FormBuilder, private router: Router) {
            this.form = this.builder.group({
              unemployed: ['', Validators.required],
              state: ['', Validators.required]
            });
          }
        
          controlFocussed() {
            this.isSubmitted = false;
          }
        
          public hasError = (controlName: string, errorName: string) => {
            return this.form.controls[controlName].hasError(errorName);
          };
        
          route() {
            this.isSubmitted = true;
        
            if (this.form) {
              if (this.form.controls['unemployed'].value === 'Y') {
                const stateControl = this.form.get('state');
                if (stateControl) {
                  stateControl.setValidators([Validators.required]);
                }
              } else {
                const stateControl = this.form.get('state');
                if (stateControl) {
                  stateControl.clearValidators();
                }
              }
        
              this.form.get('state')?.updateValueAndValidity();
        
              if (!this.form.invalid) {
                this.router.navigateByUrl("/felony");
              }
            }
          }
         }