I know about the (change) event Binding
in angular2 but i am surprised why my code is not working as expected?
My code is here..
http://plnkr.co/edit/9pSWSeqBc5oaSAtsfwNY?p=preview
When the change event is called not both condition work as expected.
(change)="holiday= !holiday && employee= !employee"
When change event is called the first time it works fine but the second time it will work only for first condition ie holiday
. In my example what I expected is both the value to be either true or false but not as expected.
Surely there is some mistake. Is there anyone who can explain the life cycle of the (change)
event properly?
You should separate them with ;
instead of &&
operator.
If first expression goes wrong, it would not evaluate the next expression.
(change)="holiday= !holiday;employee= !employee"
How
&&
operator works?
- Suppose
a && b
, if both are true then only it returns true(in short there shouldn't be anyfalse
value otherwise it will return false).- When evaluating
a && b
code will first checka
value istrue
then only the interpreter will goesb
value to evaluate it. Ifa
value it self isfalse
then it don't evaluate(check)b
's value, anda && b
expression will returnfalse
.
Before you were having holiday= !holiday && employee= !employee
. On initial load both holiday
& employee
has false
value. When you click on the checkbox
it evaluates holiday= !holiday && employee= !employee
, both holiday
& employee
value becomes true
.
Basically behind the scene when 1st holiday= !holiday
get evaluated, holiday
becomes true
to false
& holiday= !holiday
expression return latest value(returns true
), whether 2nd expression does the same thing & returns true
.
Now holiday = true
& employee = true
. When you click on the check box again. It calls change event & again try to evaluate holiday= !holiday && employee= !employee
. Where holiday= !holiday
return false
, so then as I mention above How &&
operator works? . It doesn't care about the next part of expression, and returns false
value.
Now holiday = false
& employee = true
. If you click on checkbox again, then holiday
turns out to true
& proceed to evaluate other part of expression by which employee
turns out to true
from false
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.