Angular2 - Show/Hide section on selection of radio button

若如初见. 提交于 2020-02-01 18:30:30

问题


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.


回答1:


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.




回答2:


<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



来源:https://stackoverflow.com/questions/45286978/angular2-show-hide-section-on-selection-of-radio-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!