angularangular6angular2-forms

How to set radio button checked based on condition in Angular 2


How to set checked and click event for radio button.

Scenario:

I tried something like this.

<label for="{{radio1.id}}" class="radio" (click)="radioSelected(radio1.label)">
    <input type="radio" id="{{radio1.id}}" name="optionsRadio41" value="{{radio1.value}}" required="" [disabled]="requestGroupName == 'SERVICE_GROUP'" [checked]="GroupName ==='ACCESS_GROUP'">
    <i class="skin"></i>
    <span>Within this solution</span>
</label>
&nbsp;&nbsp;&nbsp;&nbsp;
<label for="{{radio2.id}}" class="radio" (click)="radioSelected(radio2.label)">
    <input type="radio" id="{{radio2.id}}" [checked]="GroupName ==='SERVICE_GROUP'" name="optionsRadio41" value="{{radio2.value}}" required="">
    <i class="skin"></i>
    <span>Copy to a different solution</span>
</label>
<div *ngIf="radioSelectedLabel=='Within this solution'">first block </div>
<div *ngIf="radioSelectedLabel=='Within this solution'">second block</div>

How can I achieve both conditions?


Solution

  • Here is the working example, Please have a look at it.

    https://stackblitz.com/edit/angular-basic-tutorial-zaaf4q

    if you want to toggle attribute you need to do [attr.checked] instead of [checked], but in your case it will not work because you need to remove or add attibute.

    I have created the directive which is taking the object of atributes like {attributeName: boolean,attributeName2: boolean, ... } and will add or remove the attribute depends of the attribute value.