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

The appearance and functionality of the app undergo a noticeable transformation after being bundled with Webpack

After successfully migrating my Angular 2 project from SystemJS to Webpack using the latest version of Angular2-CLI, I noticed some unexpected changes in the design of the page. Despite minimal adjustments to the project files and Angular2 code during the ...

Error in Next.js when trying to use Firebase Cloud Messaging: ReferenceError - navigator is not defined in the Component.WindowMessagingFactory instanceFactory

Currently, I am in the process of setting up push notifications with Firebase in my next.js application. I have been following a guide from the documentation which you can find here: https://firebase.google.com/docs/cloud-messaging/js/receive?hl=es-419 Ho ...

JavaScript Date() function misinterpreting Unix timestamp

When creating the date using a timestamp retrieved from Firebase, I use the following code: let da = new Date(item.date.day); I have double-checked that item.date.day is indeed a timestamp and the correct one at that. However, regardless of the actual t ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

Encountering an issue: "Failed HTTP response while trying to access https://localhost:44328/api/AllItProjectsLists/Index: 0 Error Message Unknown"

I am completely new to working with Angular. I have been working on a small application that is supposed to display a list of projects retrieved from a database on the Angular side. To achieve this, I am making a call from Angular to .NET Core 2.2. The dat ...

Eliminating the nested API call within a loop

After making an API call to retrieve a set of data such as a list of users, I noticed that I am implementing a for loop and within it, I am making another API call to obtain each user's profile details based on their ID. I understand that this approac ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

Exploring the Material Drawer functionality within an Angular application

I'm having trouble integrating the Material Drawer component into my Angular app. Despite following the instructions on https://material.io/develop/web/components/drawers/, it's not rendering properly. Could someone please provide a detailed, s ...

Need help in NestJS with returning a buffer to a streamable file? I encountered an error stating that a string is not assignable to a buffer parameter. Can anyone provide guidance on resolving this issue?

The issue description: I am having trouble returning a StreamableFile from a buffer. I have attempted to use buffer.from, but it does not seem to work, resulting in the error message below. Concern in French language: Aucune surcharge ne correspond à cet ...

Encountering a 404 error when using the NestJS GET function within the service and controller

I am facing an issue with creating simple GET logic. When I test it in Postman, I keep receiving a 404 error. books.service.ts contains the following basic logic: constructor( @InjectRepository(Books) private readonly booksRepo: Repository<Boo ...

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Issues with the typings for the toPromise function in WebStorm have been identified

I'm encountering an issue with WebStorm not recognizing the typings for the toPromise function on 'rxjs', despite having updated it. Is there a way I can troubleshoot this and fix it? Strangely, the code still runs successfully despite the ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

Adding a project to TFS source control using Visual Studio Code: a step-by-step guide

Looking for guidance on adding an Angular 4 project developed with Visual Studio Code (version 1.18.0) to TFS source control. I've already installed the TFS extension (version 0.6.0) in Visual Studio Code, but unsure how to map the project folder to T ...

Enhancing State Management with Multiple @Select Decorators in NGXS

I have a variety of @Selects within a component structured like this: @Select(ItemState.getMode) mode: Observable<Item>; @Select(QuestionState.SingleQuestion) question: Observable<Question>; @Select(ItemState.getItemNames) itemNames: Observabl ...

Acquiring the url identifier along with parameters using the ActivatedRoute in Angular 2

I am attempting to retrieve a UUID from the URL (which is in the format of where uuid goes) and then utilize that UUID for an HTTP GET request. Currently, my app.component.ts appears as follows: private cardUuid: string; constructor(private service: App ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...