Home > Blockchain >  Creating 2 separate buttons for yes and no in angular
Creating 2 separate buttons for yes and no in angular

Time:10-21

I am trying to create two separate buttons to pass value of true and false as options for quiz. I have the following

public yes:boolean = false;
public no:boolean = false;

The buttons must have the same styles except when clicked. The button will change to orange. What I did was to set the yes and no to false, then use ! to alter the state when click. i.e true to apply the tailwind style. The orange background is only when the button selection is true and when the No button is true, the Yes button must be false.

    public yesButton():void {
      this.score = '';
      this.yes = !this.yes;
      this.no ? this.no = false : this.no;
      this.userChoice =  true;
     
    }

    public noButton(): void {
      this.score = '';
      this.no = !this.no;
      this.yes ? this.yes = false : this.yes;
      this.userChoice = false;
   
    }

It works fine but I want to know if I can do this with just a variable, for instance this.status instead of separate this.no and this.yes.

More also, I am using this.no and yes.no to determine the state of the buttons.

[ngClass]="{
            'bg-orange border-0 hover:text-white text-white': no, 
            'bg-white border text-gray-900 border-gray-100': !no}" 
        >

and for the yes;

[ngClass]="{
            'bg-orange border-0 hover:text-white text-white': yes, 
            'bg-white border text-gray-900 border-gray-100': !yes}" 
        >

I tried to use public status: boolean = false, instead of yes and no but the logic for ngClass failed if I click on one button, it is applicable to the other button.

CodePudding user response:

In your ts file, do this.

public userChoice!: boolean | undefined 

Note: using exclamation is to suppress the initialization error.

public yesButton():void {
      this.score = '';
      this.userChoice =  true;
     
    }

public noButton(): void {
  this.score = '';
  this.userChoice = false;

}
for yes
[ngClass]="{
        'bg-orange border-0 hover:text-white text-white': userChoice === true}" 
    >
for no
[ngClass]="{
            'bg-orange border-0 hover:text-white text-white': userChoice === false}" 
        >

Now add your default values in the . As I have done here.

CodePudding user response:

public yesButton():void {
      this.score = '';
      this.userChoice =  true;
     
    }

public noButton(): void {
  this.score = '';
  this.userChoice = false;

}
for yes
[ngClass]="{
        'bg-orange border-0 hover:text-white text-white': userChoice , 
        'bg-white border text-gray-900 border-gray-100': !userChoice }" 
    >
for no
[ngClass]="{
            'bg-orange border-0 hover:text-white text-white': !userChoice , 
            'bg-white border text-gray-900 border-gray-100': userChoice }" 
        >
  • Related