2

We have an angular2 component where we have certain radio buttons. I check the radio buttons on certain conditions.

The HTML code for radio buttons goes as:

<span class="radio-switch-group">
    <label>
	<input type="radio" name="radioView" id="All" (click)="onBtnClick('All')" [checked]="currentTab === 'All'">
	<span class="radio-label">ALL Cars</span>
    </label>
    <label>
        <input type="radio" name="radioView" id="Honda" (click)="onBtnClick('Honda')" [checked]="currentTab === 'Honda'">
        <span class="radio-label">Honda</span>
    </label>
</span>

The ts file is as follows:

     export class CarComponent implements OnInit{
         @Input() public currentTab: string = 'All';

         public onBtnClick(carType: string){
             this.currentTab = carType;
         }

         public ngOnInit() {
             this.currentTab = 'All';
         }
     }

When I instantiate this component in a tab view from another component the radio button isnt checked even when the currentTab is set to 'All'

2
  • this code is worked fine for me, please check your code anywhere else the checkbox value is clearing Commented May 8, 2017 at 11:49
  • I am instantiating this component in a tab, it doesn't work under that scenario. Commented May 8, 2017 at 14:08

2 Answers 2

1

Try using [value] attribute binding of the input. IIRC using [selected] or [checked] in Angular is essentially doing the following.

if ([checked]===[value])

<span class="radio-switch-group">
    <label>
	<input type="radio" name="radioView" id="All" (click)="onBtnClick('All')" [value]="'All'" [checked]="currentTab">
	<span class="radio-label">ALL Cars</span>
    </label>
    <label>
        <input type="radio" name="radioView" id="Honda" (click)="onBtnClick('Honda')" [value]="'Honda'"[checked]="currentTab">
        <span class="radio-label">Honda</span>
    </label>
</span>

Sign up to request clarification or add additional context in comments.

2 Comments

Single quotes inside of the double quotes! Should have realized!
@Daniel Cooke - What if I want to get the value of checked radio button on template driven form submit ?
0

Instead of @Input(), declare just a variable like below:

export class CarComponent implements OnInit{
     public currentTab: string = 'All';

     public onBtnClick(carType: string){
         this.currentTab = carType;
     }

     public ngOnInit() {
         this.currentTab = 'All';
     }
 }

@Input is responsible for one way binding in angular2.

Hope it helps!!

1 Comment

@Input is also two-way -- it depends on how the parent element is using it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.