0
\$\begingroup\$

This is short Angular 5 code which works as intended: check boxes behave like radio buttons - only one can be selected at a time.

Both versions of 'toggleCheckbox' works but I am interested is if there is better, more elegant way to set 'checkbox1' and 'checkbox2'?

template-driven-form.component.ts

import {Component, OnInit} from '@angular/core';

import {User} from './domain/user';

@Component({
  selector: 'app-template',
  templateUrl: './template-driven-form.component.html',
  styleUrls: ['./style.css']
})

export class TemplateDrivenFormComponent implements OnInit {
  user = new User();

  ngOnInit() {
    this.setDefaultValues();
  }

  constructor() {
  }

  // toggleCheckbox(event) {
  //   if (event.target.id === 'checkbox1') {
  //     this.user.checkbox1 = true;
  //     this.user.checkbox2 = false;
  //   } else {
  //     this.user.checkbox1 = false;
  //     this.user.checkbox2 = true;
  //   }
  // }

  toggleCheckbox(event) {
    event.target.id === 'checkbox1' ? (this.user.checkbox1 = true, this.user.checkbox2 = false)
      : (this.user.checkbox2 = true, this.user.checkbox1 = false);
  }

  setDefaultValues() {
    this.user.checkbox1 = true;
    this.user.checkbox2 = false;
  }
}

template-driven-form.component.html

<h3>Template Driven Form</h3>
<table>
  <tr>
    <td>
      <label for="checkbox1">Label 1</label><input type="checkbox" id="checkbox1" name="checkbox1" [ngModel]="user.checkbox1" (change)="toggleCheckbox($event)" [checked]="user.checkbox1">
    </td>
  </tr>
  <tr>
    <td>
      <label for="checkbox2">Label 2</label><input type="checkbox" id="checkbox2" name="checkbox2" [ngModel]="user.checkbox2" (change)="toggleCheckbox($event)" [checked]="user.checkbox2">
    </td>
  </tr>
</table>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.