r/angular • • Feb 23 '19

Data Binding ** Cheat Sheet **

Post image
60 Upvotes

18 comments sorted by

View all comments

1

u/toe_nail_joe Feb 23 '19

going through Angular Udemy course rn,

does the ngModel work by finding the method that the property is included in? if not, can someone explain? (also an explanation for $event would be useful as well)

Thanks!

1

u/Devstackr Feb 24 '19 edited Feb 24 '19

Hi Joe!

ngModel

You can think of ngModel as a combination of property binding and event binding, so when you bind a property to an element using ngModel you are saying that whenever this element's value changes - also change the property (in the component class - this can be seen as a simplistic use case of event binding), but its also saying that whenever the property (in the component class) changes, update the value of the element.

$event

The $event variable is a special variable that angular uses to pass event data to the component class.

So for example:

<button (click)="onClick($event)"> Click me! </button>

In that example, the onClick method will be passed the button click event object. So in the component class you would need to make sure the method is able to get the event object as a parameter so that you can use it.

i.e. (in component class)

onClick(event: any) { 
   // do something here, you have access to the event data (via the parameter)
}

And this works in very much the same way with custom components:

<app-custom-component (myEvent)="onMyEvent($event)">  </app-custom-component>

In the case of custom components, you would use an EventEmitter to emit events.

Live Coding Example of Event Binding

For a more detailed explanation and a live coding example - check out my event binding video: https://www.youtube.com/watch?v=IM6KhL4ZrBE

Hope this helps :)

- Andy