dota2pro
dota2pro

Reputation: 7864

Unable to select a radio button in Angular with click

I have very simple code, but It doesn't allow me to check the All option, How can I fix this ?

Reproducible Demo -> https://stackblitz.com/edit/angular-tbanxq?file=src%2Fapp%2Fhello.component.ts

import { Component, Input } from "@angular/core";

@Component({
  selector: "hello",
  template: `
    <h1>Hello {{ name }}!</h1>

    <div>
      <input
        type="radio"
        name="commentType1"
        value="foo"
        id="rdobuy"
        (click)="showSelection = false"
      />
      <label class="radio-label" for="rdobuy">All</label>
    </div>

    <div>
      <input
        type="radio"
        name="commentType1"
        value="bar"
        id="rdosell"
        (click)="showSelection = true"
      />
      <label for="rdosell" class="radio-label">Selection</label>
    </div>


    <div *ngIf="showSelection">Hello</div>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;
}

Upvotes: 0

Views: 2570

Answers (2)

emtei
emtei

Reputation: 631

Its because (click) with anything that is falsy. Stops event propagation, this block native "check" reaction.

You can create a handler function

export class HelloComponent {
  @Input() name: string;
  showSelection: boolean;

  setSelection(newVal: boolean) {
    this.showSelection = newVal;
  } 
}

and then call it in template:

(click)="setSelection(false)"

Working example: https://stackblitz.com/edit/angular-putvsm?file=src/app/hello.component.ts

Upvotes: 1

AliF50
AliF50

Reputation: 18889

Try this, leveraging (change) and [checked]:

I think a (click) on the first one was getting bad results.

     <div>
      <input
        type="radio"
        name="rdobuy"
        [checked]="!showSelection"
        value="foo"
        id="rdobuy"
        (change)="showSelection = false"
      />
      <label class="radio-label" for="rdobuy">All</label>
    </div>

    <div>
      <input
        type="radio"
        name="rdosell"
        [checked]="showSelection"
        value="bar"
        id="rdosell"
        (change)="showSelection = true"
      />
      <label for="rdosell" class="radio-label">Selection</label>
    </div>

Upvotes: 1

Related Questions