How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, 'displayConflict' should be set to true.

I attempted to solve this problem using the following code but couldn't find a solution:

 <input #m [checked]="model.Gender == m.value" (click)="model.Gender = m.value" name="Gender" value="male" type="radio">
<input #f [checked]="model.Gender == f.value" (click)="model.Gender = f.value" name="Gender" value="female" type="radio">


<p-button (click)="showExist(model.Gender);" pButton type="button" label="Accept"></p-button>

private display: boolean = false;
public displayConflict: boolean = false;
public showExist(str: String): void {
        if (str === "male") {
            this.display = false;
        } else {
            this.displayConflict = true;
        }
    }

Answer №1

Below is a functioning example:

// Here we have our root app component
import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>

    <label>Male</label>
      <input #m [checked]="model.Gender == m.value" (click)="model.Gender = m.value" name="Gender" value="male" type="radio" />
      <label>Female</label>
<input #f [checked]="model.Gender == f.value" (click)="model.Gender = f.value" name="Gender" value="female" type="radio" />
<br/>
<button (click)="showExist(model.Gender);" pButton type="button" label="Accept">
Next</button>

<div *ngIf="!display || displayConflict"> Hide me, by selecting and hitting Next</div>

    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2 (Release Candidate!)'
  }

  model:any={"Gender": "female" }
  private display: boolean = false;
public displayConflict: boolean = false;
public showExist(str: String): void {
        if (str === "male") {
            this.display = false;
            this.displayConflict = true;
        } else {
          this.display = true;
            this.displayConflict = false;
        }
    }
}

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

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

Is it feasible to set an empty object as the initial default value in the state of a React component?

In my React application with TypeScript, I am using "react": "^17.0.0". Here is how I define the app state: export interface IRoleState { data: API.RoleItem, menus: API.MenuItem, } When I set up the initial state like this: con ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Filtering in RxJS pipelines can be compared to an if-else statement

I'm not very familiar with JS and RxJS, so please pardon me if my question seems trivial. Here is a code snippet that I didn't write: prepare(): Observable<any> { const i = of({}).pipe( // Check if file type is image fil ...

Establish a connection between an Angular client and a Spring backend using JWT for authentication

I successfully integrated JWT into my Spring backend by following the steps outlined in this informative guide: https://auth0.com/blog/securing-spring-boot-with-jwts/ Interestingly, when I perform a PUT request using Postman, everything seems to be workin ...

Issue with Dynamic Theming in Ionic Framework

Currently, I am using Ionic in combination with Angular to create an App. I have introduced dynamic theming by adding two .scss files into my theme folder. In my app.scss file, I define the layout of components without colors, while all color styles are st ...

Testing Angular conditions for tab selection

Looking for a solution with angular: <li><a href="#tab_2-2" target="_self" data-toggle="tab">Test</a></li> If the checkbox named "test" on the first tab is not checked, I want the above tab to be disabled. I'm seeking hel ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

Utilize Ionic Auth Connect to establish the currentSession and currentAuthenticatedUser on AWS Amplify

Problem with Amplify Configuration In the process of developing a new ionic app, our team decided to utilize AWS Amplify as our backend solution. To interact effectively with various services, we opted to use both "AMAZON_COGNITO_USER_POOLS" and "API_KEY" ...

Having trouble injecting ActivatedRouteSnapshot into the component

Struggling to inject ActivatedRouteSnapshot into a component, encountering errors when trying to access query params. Here is the error stack trace: "Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?). a ...

Using Angular 2 to implement a custom dropdown feature with the ngModel directive

I've created a unique custom component that displays employment types in a dropdown menu and allows the user to select one. Here is the code for the component: import { Component, OnInit } from "@angular/core"; import { EmploymentType } from '. ...

When utilizing makeStyles in @mui, an error may occur stating that property '' does not exist on type 'string'

I am stuck with the code below: const useStyles = makeStyles(() => ({ dialog: { root: { position: 'absolute' }, backdrop: { position: 'absolute' }, paperScrollPaper: { overflow: 'visib ...

The 'localstorage' object is not defined in NextJS 14, make sure to use 'client' in server-side execution

While setting up the Tailwind context for a Next.js 14 website, I encountered an issue with configuring a global theme for my project. Despite creating the ThemeContext and adding 'use client' at the beginning of the file, it still caused an erro ...

"Customizing API requests based on specific conditions with n

For a specific scenario, I need to login as an admin in one case and as a regular user in another. signIn$ = createEffect(() => this.actions$.pipe( ofType(AuthActions.signInRequest), exhaustMap(({ variables, redirectTo, hasAdmin }) =&g ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

What is the best way to toggle the visibility of the ng-bootstrap datepicker-popup component?

Is there a way to toggle the visibility of the ng-bootstrap datepicker-popup by setting a property to 'true' or 'false'? In my form, I have the following snippet and I only want to show the entire div section if the user chooses to inp ...

Invoke numerous HTTP requests and receive multiple observables in response

When attempting to call multiple HTTP requests and combine several observables into one, I am facing an issue where only the last one is being emitted. I have an input field with a form control called "ctl" where users can input a keyword to search for cus ...

What is the proper way to implement ref in typescript?

Currently, I am in the process of learning how to use Vue3 + Typescript. Previously, I have developed Vue2 applications using plain JavaScript. In my current project, I am attempting to define a reactive variable within the setup() function: setup() { ...

Encountering a sign-in issue with credentials in next-auth. The credential authorization process is resulting in a

I am currently facing an issue with deploying my Next.js project on Vercel. While the login functionality works perfectly in a development environment, I encounter difficulties when trying to sign in with credentials in Production, receiving a 401 error st ...