Deselect radio button in Angular 7 using Bootstrap 4 styling

Seeking assistance with using Angular 7 and Bootstrap 4 to create radio buttons that can toggle on and off. I came across a solution here. Check out my current method.

Currently, I am able to toggle the buttons, however, I now face a new dilemma. I want each row to be independent, allowing users to select a different answer for each row or leave it blank.

My main query is: How can I enable users to select a different answer for each row or leave it blank? Is there a way to uniquely identify each row in the code?

Your help is greatly appreciated.

Answer №1

update: Although it may seem a bit hardcoded, this serves as a solid foundation: .ts:

  status: boolean = false;
  option=""
  option1=[false, false, false]
  option2=[false, false, false]
  option3=[false, false, false]

  constructor(private renderer: Renderer2){}


  data = [{
    id:"1a",
    One:"Yes-1a",
    Two:"Maybe-1b",
    Three:"No-1c"
  },{
    id:"2a",
    One:"Yes-2a",
    Two:"Maybe-2b",
    Three:"No-2c"
  },
  {
    id:"3a",
    One:"Yes-3a",
    Two:"Maybe-3b",
    Three:"No-3c"
  }
  ]

  clickEvent1(i){
    this.option = 'option1 : ' + this.option1
    if(this.option1[i] == true){
      this.option1[i] = false
    }else{
      this.option1[i] = true
    }  
    this.option2[i] = false; this.option3[i] = false


}
  clickEvent2(i){

    this.option = 'option2 : ' + this.option2
    if(this.option2[i] == true){
        this.option2[i] = false
     } else{
        this.option2[i] =true
     }
      this.option1[i] = false; this.option3[i] = false
}
  clickEvent3(i){

    this.option = 'option3 : ' + this.option3
    if(this.option3[i] == true){
      this.option3[i] = false
    }else{
      this.option3[i] = true
    }
      this.option1[i] = false; this.option2[i] = false} 
}

.html:

<div class="card" style="height:400px">
  <div class="card-body no-gutters">

    <div *ngFor="let radio of data" class="btn-group-toggle" data-toggle="buttons">
      <div class="row">
        <label class="btn btn-secondary col-4" 
        [ngClass]="option1 ? 'bbb' : ''">
          <input (click)="clickEvent1()" 
          type="radio" name="options" id="option1">
          {{radio.One}}
        </label>
        <label class="btn btn-secondary col-4"
        [ngClass]="option2 ? 'bbb' : ''">
          <input (click)="clickEvent2()"
          type="radio" name="options" id="option2" autocomplete="off"> {{radio.Two}}
        </label>
        <label class="btn btn-secondary col-4"
        [ngClass]="option3 ? 'bbb' : ''">
          <input (click)="clickEvent3()"
          type="radio" name="options" id="option3" autocomplete="off"> {{radio.Three}}
        </label>
        {{option}}
      </div>
    </div>


  </div>
</div>

//Apologies for my lack of knowledge on saving changes on stackblitz :(

Answer №2

After much searching, I have finally stumbled upon the perfect fix for my issue. Check it out here: How to toggle a radio button's state on the second click in Angular 2+.

This solution is not only easy to implement, but also highly adaptable and efficient.

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

After the initialization of the app, make sure to provide an InjectionToken that includes the resolved configuration

During the initialization of the application, I am looking to retrieve the configuration using a factory that will be resolved through the APP_INITIALIZER provider. export function loadConfig(): () => Promise<Config> { // return promised confi ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...

Guide to integrating Keycloak into Angular 6 applications

Looking for assistance on integrating Keycloak into Angular 6. Unsure of where to begin and how to initiate the Javascript Adapter. Can anyone lend a hand? ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

What is the best way to extract the ng-reflect-value and compare it with the expected value in testing?

After reviewing the attachment, I am utilizing the following code snippet "private readonly By _idTxt = By.XPath(".//*[@class='metric-set-details-dropdown']/../button[ng-reflect-value]");" in an attempt to extract the value of the attribute ng-re ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Developing a foundational Repository class in TypeORM

Are you looking to create a custom baseRepository class that extends TypeORM's Repository? import { Repository } from 'typeorm'; export abstract class BaseRepo extends Repository<T> { public getAll ( ...

Reacting to Appwrite events in a React Native environment

My React Native application encounters an error when subscribing to realtime events. The error message reads as follows: ERROR Error: URLSearchParams.set is not implemented, js engine: hermes. appwriteClient .subscribe( `databases.${APPWRITE_DATAB ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Utilizing arrayUnion function in Firestore with Angular

My journey to learn Firestore has hit a roadblock. The documentation on AngularFire and FieldValue hasn't been much help. Every time I try to use FieldValue, it throws an error saying "FieldValue does not exist." const userRef = this.firestore.collect ...

Having trouble with subscribing to a template in Ionic framework

I'm attempting to showcase an image from Firebase storage using the following code: Inside my component : findImg(img) { this.storage.ref('/img/' + img).getDownloadURL().subscribe( result => { console.log(result); ...

Creating a record type with specific keys associated with values while leaving the rest undefined

Consider the scenario where the following code is implemented: const myObj = { "hello": "world"; } as const; const anyString: string = "Hi" if (myObj[anyString]) { // Element implicitly has an 'any' type because ...

Enhancing Error Handling in Node.js with TypeScript Typing

Currently, I am working with NodeJs/express and Typescript. When making a request, the compiler automatically understands the type of (req, res), requiring no additional action on my part. UserRouter.post('/user/me/avatar', avatar, async (req, ...

Creating a custom string subtype in TypeScript

I am currently working on developing a game called Risk using TypeScript and React hooks. This game is played on a map, so my first step was to design a MapEditor. The state of the Map Editor is as follows: export interface IMapEditorState { mousePos: ...

Encountering an Issue with the Development Server in React and TypeScript

My attempt to set up a new TypeScript-React project using the command npx create-react-app todo-list --template typescript was successful in terms of installation. However, when I tried to run the project with npm start I encountered the following error: ...

Issue encountered when transitioning from Angular 8 to Angular 9: Value discrepancy at index 0

While updating my Angular project from version 8 to 9, I encountered an issue after following the update guide on update.angular.io and running npm update. When attempting to compile the website using ng serve, the following error occurred: ERROR in Faile ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Typescript encountering issues with addEventListener

const [status, setStatus] = useState<string>("pending"); const updateStatus = (newStatus: string) => { setStatus(newStatus); }; useEffect(() => { window.addEventListener("updateProtocol", updateStatus); return () =&g ...