reveN
reveN

Reputation: 642

Angular 4 form validation with input fields and checkboxes

I have this form right here:

<form (ngSubmit)="onSubmit()" #testForm="ngForm">

  <div class="form-group col">
    <label for="a">a</label>
    <select class="form-control" id="a" [(ngModel)]="form.a" name="a" required>
      <option value="x">x</option>
      <option value="y">y</option>
    </select>
  </div>

  <div class="form-group">
    <label for="b">b</label>
    <input class="form-control" id="b" [(ngModel)]="form.b" name="b" required />
  </div>

  <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" class="form-check-input">c
    </label>
  </div>

  <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" class="form-check-input">d
    </label>
  </div>

  <div class="col text-right">
    <button type="submit" class="btn btn-success" [disabled]="!testForm.form.valid">Submit</button>
  </div>

</form>

With this component-code behind:

export class FormComponent {
  form = new Form();
  submitted = false;
  onSubmit() {
    this.submitted = true;
  }
}

What I want to achieve is that my button only gets enabled, when both the dropdown and the input field are filled in, which works with the required attribute, AND both checkboxes are checked, which doesn't work.

My question: Is there something like required for Checkboxes, or are there other ways to solve this problem?

Upvotes: 0

Views: 1935

Answers (1)

Daniel Segura P&#233;rez
Daniel Segura P&#233;rez

Reputation: 1117

Try this way:

 <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" [checked]="ch2" (change)="ch2= !ch2" class="form-check-input">c
    </label>
  </div>

  <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" [checked]="ch1" (change)="ch1= !ch1" class="form-check-input">d
    </label>
  </div>

  <div class="col text-right">
    <button type="submit" class="btn btn-success" [disabled]="!testForm.form.valid || !ch1 || !ch2">Submit</button>
  </div>

Upvotes: 1

Related Questions