Submit a form when my input is checked Angular

Viewed 50

Hello everyone I am on rating-app component and i want to submit my form only if I have a notation checked ( 1,2,3,4,5 ) but i create all my input with an *ngFor so when i try to do it with *ngModel only an element is triggered and i don't understand why, if someone can help me it will be great !

this is my repo : https://github.com/qalimero/rating-app

My HTML :

 <main role="main">
  <div *ngIf="!display; then displayRate else displayResult"></div>
  <ng-template #displayRate>
    <div class="header-rating" role="heading">
      <fa-icon [icon]="faStar"></fa-icon>
      <h1>How did we do ?</h1>
    </div>
    <p class="text-body">
      Please let us know how we did with your support request. All feedback is 
      appreciated to help us improve our offering!
    </p>
    <form>
      <ul class="radio-wrapper">
        <li *ngFor='let radio of radios; let idx = index' [ngClass]="['radio']">
          <input [(ngModel)]="!isChecked" class="visually-hidden" id="rate_{{ idx }}" 
                 name="rate" type="radio">
          <label [ngClass]="['custom-checkbox']"
                 for="rate_{{ idx }}">{{ radio }}</label>
        </li>
      </ul>
      <button (click)="submitResult()" [disabled]="isChecked ===false" 
       type="button">SUBMIT</button>
    </form>
  </ng-template>
  <ng-template #displayResult>
    <div class="header-result">
      <img src="../../assets/images/illustration-thank-you.svg">
      <p class="resume-result">You selected 4 out of 5</p>
      <h2>Thank you!</h2>
      <p>We appreciate you taking the time to give a rating. If you ever need more 
         support, don’t hesitate to get in touch!
      </p>
    </div>
  </ng-template>
</main>

Ts :

import {Component} from '@angular/core';
import {faStar} from "@fortawesome/free-solid-svg-icons";

@Component({
  selector: 'app-rating-component',
  templateUrl: './rating.component.html',
  styleUrls: ['./rating.component.scss']
})
export class RatingComponent {
  display = false;
  faStar = faStar;
  radios = ['1', '2', '3', '4', '5'];
  isChecked = false;

  constructor() {

  }

  submitResult() {
    this.display = !this.display;
  }
}
1 Answers

[(ngModel)] does not really support radio buttons properly. You can implement two way binding using [value] and (change) but it's not necessary.

The nature of radio buttons is that once one is selected, there will always be one selected. It is impossible for the user to deselect all members of the group. So you can just use the (change) callback, and set isChecked to true on the first change.

<li *ngFor='let radio of radios; let idx = index' [ngClass]="['radio']">
  <input (change)="isChecked = true" ... > // Remove ngModel
  ...
</li>
Related