0

I have a checkbox that I need the value to reflect the boolean in the data model and disregard attempts by the user to change it.

Here is an example of my setup:

Data model

const item = {label: 'test', active: false, selected: false};

Template with various inputs I have tried:

<li (click)="item.selected = !item.selected" [class.selected]="item.selected">
  <input type="checkbox" [ngModel]="item.active">
  <input type="checkbox" [value]="item.active">
  <input type="checkbox" [checked]="item.active">
  {{item.label}}
</li>

Since the active state in the data is not being changed (not 2 way bound) I would expect the checkbox to always remain in the un-checked state despite the user trying to check it.

This is not the case, however. The user can still check the box and the active state is still false, yet the selected state changes. What is preventing change detection from seeing that the checkbox DOM state is different than the model when that model has changed?

Does the change detection only watch the specific DOM elements and since the active state hasn't changed it assumes the DOM hasn't been affected?

How do I get change detection to see this change and utilize the model value accordingly?

2 Answers 2

2

You can add (click)="false" in the input tag. That you stop the checkbox from toggling in the DOM.

<input type="checkbox" [ngModel]="item.active" (click)="false">{{item.label}}

Here's the Plunker Demo.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to work best for my use case without having to re-style anything. Thanks
Wierd hack, but it works! Thanks! Don't know why though. I made a function that does some checks and returns false if the checkbox should not toggle, and it works! I have a side-effect in this function, so I could not use [disabled].
0

I would suggest just disabling the checkbox all together

<input type="checkbox" [ngModel]="item.active" disabled="true">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.