Reputation: 9648
I was searching for the ng-true-value
and ng-false-value
alternatives in Angular 2
but i didn't get a result. Did they replace them with other tools ? I really need them. Thanks in advance
Upvotes: 15
Views: 9619
Reputation: 148
Use below directive from npm. It is alternative to the ng-true-value and ng-false-value in angular 2 https://www.npmjs.com/package/@nikiphoros/ngx-toggle
Upvotes: 0
Reputation: 4203
I think Experimenter answer is too long, so i am giving short one:
<input type="checkbox" [(ngModel)]="isActive" [checked]="isActive" name="active" (change)="isActive ? data.is_active = 1 : data.is_active = 0">
I am using just short-if.
Upvotes: 2
Reputation: 2478
Workaround. For example we have the 'object' in the model with a 'flag' and one checkbox should set the flag to value "1" and another checkbox should set the flag to value "2", if the checkbox both unchecked the value should be "0", so:
public setFlag(object: any, event: any): any {
if (event.target.classList.contains('some-mark-class') && (object.flag == 0 || object.flag == 1)) {
object.flag = 2;
} else if (!event.target.classList.contains('some-mark-class') && (object.flag == 0 || object.flag == 2)) {
object.flag = 1;
} else {
object.flag = 0;
}
}
<input type="checkbox" name="hide-{{object.flag}}" [checked]="object.flag === 1" (change)="setFlag(object, $event)">
<input type="checkbox" name="dlte-{{object.flag}}" [checked]="object.flag === 2" (change)="setFlag(object, $event)" class="some-mark-class">
The solution might be not perfect and somehow clumsy but it's something and it works, so if you have some improvements, please do.
When I'll have some more time I'll try to do it in some sandbox if you want :).
UPDATE: Verson 2 Better approach and flexibility
.ts file:
public setFlag(obj: any, property: any, trueValue: any, falseValue: any): any {
if (obj[property] === trueValue) {
obj[property] = falseValue;
} else {
obj[property] = trueValue;
}
}
<input type="checkbox" name="hide-{{object.flag}}" [checked]="object.flag === 1" (change)="setFlag(object, 'flag', 1, 0)>
<input type="checkbox" name="dlte-{{object.flag}}" [checked]="object.flag === 1" (change)="setFlag(object, 'flag', 'true-value', 'false-value')>
In a function setFlag we take 4 parameters: object, property for the object, true-value and false-value which give us flexibility to set the value what we wish and do it without mark-class. Hope it helps
Upvotes: 2