angularangular-ui-router

How to create a required error message when I click the button before going to the next page?


I'm trying to create an error message on my textbox and dropdown questions where when I click next to go to the next page it shows an error message that these are required so I must enter something before going to the next page.

component.html

<div class="container tb-10">
<form>
    <div>
        <div class="row">
            <h4>TANF - Temporary Assistance to Needy Families:</h4>
            <div class="form-group">
                <label>Please name the person (whether you or a member of your household) who receives food stamps, and city and state where they are received.</label>
                <div>
                    Person Receiving Benefits: <input type="text" class="form-control" name="tanf_beneficiary" id="tanf_beneficiary" required placeholder="Person Receiving Benefits" >
                </div>

                <div>
                    Relationship to you: <input type="text" class="form-control" name="tanf_relationship" id="tanf_relationship" required placeholder="Relationship to you" >
                </div>

                <div>
                    City: <input type="text" class="form-control" name="tanf_city" id="tanf_city" required placeholder="City" >
                </div>

                <div>
                    <label for="state" class="form-label">State:</label>
                    <select class="form-select" value="" aria-label="State"  id="state">
                        <option selected>Select State...</option>
                        <option value="1">One</option>
                        <option value="2">Two</option>
                        <option value="3">Three</option>
                    </select>
                </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 pull-right"  routerLink="/unemployed"> Next </button>
    </footer>
</form>

component.ts

import { Component } from '@angular/core';

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

}

Solution

  • There are various ways to handle forms in Angular. I am sharing a simple way as per your requirement. I have not used the material library since in your example you used simple controls. Here is a code sample I created

    We use formGroup to handle form submission and error handling.