How can we recreate this ngModel text input form in a radio format for a spring boot mvc and angular application?

As I was following a tutorial on creating an employee CRUD model using spring boot and mysql server for the backend and angular for the frontend, I encountered a form group during the creation process. The tutorial originally had a text input field for gender, but I wanted to change it into radio buttons.

<div class="form-group">
            <label>
                Gender </label>
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">
        </div>

The above code snippet worked successfully for submitting the form with the text input field, but when I attempted to convert it into radio buttons, the submission action didn't work as expected. Here is what I tried based on a radio button example:

<div class="form-group">

            <label for [(ngModel)]="employee.gender">Gender:</label>
            <div>
                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                <label for="male">Male</label>
            </div>

            <div>
                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                <label for="female">Female</label>
            </div>
        </div>

I am still learning and my understanding of these concepts could use some improvement. Any assistance or guidance on how to correctly implement radio buttons in this scenario would be greatly appreciated. Thank you!

Answer №1

When working with Forms in Angular, you have the option to choose between two different approaches:

Template-driven forms utilize ngModel for data binding, while Reactive forms involve working with FormControls.

The first code example provided uses the Template-driven approach, specifically showing how to implement radio buttons for selecting gender:

<div class="form-group">
  <label>Gender:</label>
  <div>
    <input id="male" type="radio" value="male" name="gender" [(ngModel)]="employee.gender">
    <label for="male">Male</label>
  </div>

  <div>
    <input id="female" type="radio" value="female" name="gender" [(ngModel)]="employee.gender">
    <label for="female">Female</label>
  </div>
</div>

If using Reactive forms instead, simply replace

[(ngModel)]="employee.gender"
with
formControlName="gender"
, assuming that a FormControl named gender has been defined within your FormGroup.

Answer №2

If you need to assign the gender of an employee using radio buttons, you can follow this approach:

Group the radio buttons together and utilize the (change) event to handle setting the genders. I have provided an example below that should meet your requirements. Simply modify the example by updating the onChange(event: any) function to assign the selected value to the employee.gender.

<mat-radio-group aria-label="Select an option" (change)="onChange($event)">
  <mat-radio-button value="1">Option 1 Male</mat-radio-button>
  <mat-radio-button value="2">Option 2 Female</mat-radio-button>
  <br>
  <br>
  Selected value: {{selectedValue | json}}, send to backend sex as: {{selectedSexObj | json}}
</mat-radio-group>
@Component({
  selector: 'radio-overview-example',
  templateUrl: 'radio-overview-example.html',
  styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
  selectedSexObj = { male: false, female: false };
  selectedValue: any;
  onChange(event: any) {
    this.selectedValue = event.value;
    if (event.value == 1) {
      this.selectedSexObj = { male: true, female: false };
    } else {
      this.selectedSexObj = { male: false, female: true };
    }
  }
}

For a live demonstration, you can visit the following link: https://stackblitz.com/edit/angular-qggcqg-qydurn?file=src%2Fapp%2Fradio-overview-example.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

ErrorHookWebpack: When executing npm build in the node container, the service is detected as inactive

Encountering an issue when executing npm run build within a container on Kubernetes during a gitlab-ci job. It's worth noting that npm install, npm run lint, and npm run test all completed without any problems. Error: node@runner-7gbsh-sz-project-966 ...

Sometimes the PDF does not display even though the iframe src attribute is updating in Angular 6

I have encountered an issue with displaying a PDF file in my code. Sometimes the PDF shows up correctly, but other times it fails to load. I even tried using an iFrame instead of embed but faced the same scenario. Can anyone provide assistance? Here is my ...

What is the process for applying this specific style to a certain element?

Here is an example of an element in an Angular2 app: <div class="ticket-card" [ngStyle]="{'background': 'url(' + ticketPath + ')' , 'background-size': 'cover'}"> I would like to enhance the style b ...

Sending data to an API in order to update an object can be accomplished when the controller is handling an Observable within Angular 6

Currently I am utilizing Angular 6 for creating a few basic features and encountering some difficulties with Observables. In one of my components, I retrieve a project on initialization: ngOnInit() { this.project$ = this.route.paramMap.pipe( sw ...

What is a way to incorporate two ngClass directives within a single div element?

Is it possible to include two ng-class directives within a single div element? If so, how should we go about writing them together? Thank you for your help. <div [ngClass]={'white-background': policyNumber.length <= 0} [ngClass]="getS ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

Revving up the RxJS Engine: Unleashing the Potential of race

I'm currently working on implementing a unique input component that will execute a search when either the input value changes (with a debounce of 500ms) or when the enter key is pressed. My goal is to avoid emitting the search term twice - once on the ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Resolve the type of the combineLatest outcome in RxJS

Encountering this scenario frequently in Angular when working with combineLatest to merge 2 observables that emit optional values. The basic structure is as follows: const ob1: Observable<Transaction[] | null>; const ob2: Observable<Price[] | nul ...

Following the update to Angular 6, an error was encountered: CssSyntaxError:

Currently, I am in the process of upgrading my Angular 5 application to Angular 6. Following all the necessary steps outlined on update.angular.io, I have encountered a compilation error that persists even after completion of the upgrade process. The err ...

Using asynchronous functions in a loop in Node.js

Although this question may have been asked before, I am struggling to understand how things work and that is why I am starting a new thread. con.query(sql,[req.params.quizId],(err,rows,fields)=>{ //rows contains questions if(err) throw err; ...

Issue with passing an Angular or Ionic object to a view

Currently facing an access issue in my home.ts file where I am unable to retrieve object values in home.html using {{detail.ID}} senddata(){ this.httpClient.get('http://queenstshirtdesigner.com/wp-json/posts/'+this.id, { header ...

Utilizing Angular to render JSON data on the screen

Currently, I have my data saved in a database and am retrieving it in Angular. The problem arises when I attempt to display the data as I encounter an error. All I want is to exhibit the question in HTML using ngFor. Being new to Angular, any advice or gui ...

Angular: navigate to a different page dynamically without triggering a refresh of the current page

Within my EditUserComponent, I am utilizing a path parameter called id. If the id is invalid, I would like to redirect to either the home page or an error page without having to refresh the entire page. Is there a way to achieve this without updating the ...

The type 'unknown' cannot be assigned to type 'KeyboardEvent'. Error in file 'ts' (2345)

Currently delving into TypeScript and Angular, I encountered an issue in my textbook with an example that refuses to compile. I am unsure of how to resolve this problem. Below is the malfunctioning function: ngOnInit(): void { const logger = fromEvent ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...