3

Having some troubles reversing the checkbox value in Angular 2.

In Angular 1.x we could make a directive like below.

.directive('invertValue', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.unshift(function(val) { return !val; });
      ngModel.$formatters.unshift(function(val) { return !val; });
    }
  };
})
2
  • you mean making it false if its true? Commented Jun 15, 2017 at 2:03
  • Yeah the value is in my object is true however the checkbox should display as false. Without changing ngModel to false. i was hoping to create this as a directive so its reusable like the above code Commented Jun 15, 2017 at 2:05

1 Answer 1

7

why you need directive for this simple thing

you can achieve like this

<input type="checkbox" [checked]="!value" (change)="value= !value" />
Sign up to request clarification or add additional context in comments.

1 Comment

Does anybody know a drawback of this solution? For exaple by omitting ngModel from the element? Because it was my first solution but I could not make ngModel reversed. For now it looks fine :)

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.