angularbindingradio-button

Angular to display some content based on radio button selected


I have two radio buttons. When I select "Partially paid", then input element formControlName="paidamount" will be displayed in screen along with <div class="formGroup". I have used binding, but this is not working.

<mat-radio-group aria-label="Select an option" formControlName="fullypaid" [(ngModel)]="fullypaidvalue">
    <mat-radio-button value="true" [checked]="true">Fully Paid</mat-radio-button>
    <mat-radio-button value="false">Partially Paid</mat-radio-button>
  </mat-radio-group>
  <p>{{fullypaidvalue}}</p>
  <div class="formGroup" [class.d-none]="fullypaidvalue">
    <label for="paidamount" class="form-label" style="margin-top: 10pt;">Paid Amount</label>
    <input type="text" class="form-control form-control1" id="paidamount" formControlName="paidamount"
      placeholder="paidamount" name="paidamount" style="margin-left: 20pt;">
  </div>

enter image description here

My stackblitz link is https://stackblitz.com/github/reegan2024/mygithubrepo?file=README.md

Can someone please help me


Solution

  • Simply change these values in the template:

    <mat-radio-button value="true" [checked]="true">Fully Paid</mat-radio-button>
    <mat-radio-button value="false">Partially Paid</mat-radio-button>
    

    for

    <mat-radio-button [value]="true" [checked]="true">Fully Paid</mat-radio-button>
    <mat-radio-button [value]="false">Partially Paid</mat-radio-button>
    

    As a sidenote, I notice that you use [(ngModel)] and formControlName on the same control. No need to mix. Your form is already built using the ReactiveForms module, keep it that way.

    Remove [(ngModel)] and replace your binded value with this instead, in your component:

    get fullypaidvalue(): boolean {
      return this.productFormarray.get('fullypaid')?.value;
    }