Search code examples
angularangular-formsangular-template

Angular how to avoid a checkbox from being checked?


When a checkbox is clicked I show a modal with two buttons, accept and do not accept. The checkbox should only be checked if accept button is checked.

For testing purposes I tried to create this checkbox

<input type="checkbox" (change)="foo()" [checked]="false">

Expecting it to execute foo method of my component but never get checked. The problem is that it gets checked! I coming from React background and this is very frustrating.

Any idea what I'm doing wrong?

I also tried

<input type="checkbox" name="show_recurrency" (change)="foo()" [(ngModel)]="checkout.recurrency" id="show_recurrency" />

        foo(e) {
          e.preventDefault();
          console.error('foooooooooooooooo', e);
          this.checkout.recurrency = false;
          return;
        }

Regards,


Solution

  • You can handle the click event:

    <input type="checkbox" (click)="foo($event)" [checked]="false">
    

    and call event.preventDefault() to prevent the change:

    foo(event) {
      event.preventDefault();
      console.log("foo was called");
    }
    

    See this stackblitz for a demo.