Angular2 - Show/Hide section on selection of radio button
Asked Answered
B

2

12

I have to show or hide sections based on selection of radio button

 <input name="options"  [(ngModel)]="options" type="radio" [value]="true" [checked]="options==true"/> Yes

    <input name="options"[(ngModel)]="options" type="radio" [value]="false" [checked]="options==false"/> No</label>

<div>
      <h2 ng-show="options == 'true'">Supply</h2>
      <h2 ng-show="options == 'false'">Demand</h2>
</div>

If the user clicks on Yes then we have to show 'Supply' and hide 'Demand' If the user clicks on No then we have to show 'Demand' and hide 'Supply.

But now while loading the form itself both Supply and Demand is displaying on the screen.

Blitzkrieg answered 24/7, 2017 at 17:51 Comment(4)
Angular 2 doesn't have ng-show directive, use *ngIf instead,Nilotic
or use [hidden]="!options" on supply / [hidden]="options" on demandGlyoxaline
Thank you. It worksBlitzkrieg
@Blitzkrieg and if i want leave one option already checked? How can i do?Bogor
N
24

In Angular it can be achieved with *ngIf:

 <input name="options"  [(ngModel)]="options" type="radio" [value]="true" [checked]="options"/> Yes

 <input name="options"[(ngModel)]="options" type="radio" [value]="false" [checked]="!options"/> No

 <h2 *ngIf="options">Supply</h2>
 <h2 *ngIf="!options">Demand</h2>

And no need to check if option==true or false, [checked]="options" and [checked]="!options" do the same.

Nozicka answered 24/7, 2017 at 17:59 Comment(2)
Vega or Bob, what if there is a need to have more than two radio buttons and h2 elements on the page? Please advise.Gangling
@GGG, keep an array of the flag value and iterate thru ngfor. instead of "options" here, check that array element value with ngfor index. Hope it's clearNozicka
O
7
<div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="model.prop" name="prop" value="A">A</label>
            </div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="model.prop" name="prop" value="B">B</label>
            </div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="model.prop" name="prop" value="C">C</label>
            </div>
    </div>

<div *ngIf="model.prop === 'A'">A</div>
<div *ngIf="model.prop === 'B'">B</div>
<div *ngIf="model.prop === 'C'">C</div>

if you want to preselect the value type then type

 model.prop = 'A';

in your .ts file

Onlybegotten answered 6/9, 2017 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.