Issue
I have the following input
//html
<input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" >
// in the ts file
onSelection() {
alert('changed');
}
When I type something inside the input, the onSelection
methods is called. But When I try to set selectedNode
by another methods the function is not triggered.
For example I added these codes:
// html
<button (click)="settest();">
click to change value (but does not fire ngModelChange)
</button>
//ts
settest() {
this.selectedNode = 'test';
}
I expect when I call the settest()
methods ngModelChange
fires but that is not happened. Why?
Solution
I kind of curious about this question so I debug it a little bit. The reason turned out is shockingly simple: They are just 2 different things.
- The event binding:
(ngModelChange)
is triggered by ViewToModelUpdate comes fromDefaultValueAccessor (image below)
- Your
settest
is aclick
event, you see, click event isn't handled byDefaultValueAccessor
(or in general ControlValueAccessor), so no trigger on modelChange
If none of the above make any sense to you. The key take away is: when typing in -> it's View->Model
which is very different from setting the model directly
as you do in your click handler.
For more info about ControlValueAccessor and ViewToModel/ModelToView
Edited with some kind of eli5:
- First case: When you enter some text into the input. You're telling angular: hey angular, I've got this text (view), help me set it to my class property (model). Angular needs the help of DefaultValueAccessor to do the job: View -> DefaultValueAccessor (along the way fire the event ngModelChange) -> Model.
- Same story for the second case: Hey angular, user clicked this button. Angular got it and run the click handler function which in turn simple set: class' property = new value - No DefaultValueAccessor get involved no ngModelChange event triggered
Answered By - Jimmy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.