what is the difference between event binding and property binding?

烈酒焚心 提交于 2021-02-17 21:54:12

问题


In the architecture of angular 2 there are two terms Event binding and Property binding. What is the difference between them?


回答1:


Property binding -

In case you have to pass the value from parent component to child component (whether the value is static or dynamic) we have to use the property binding that mean by doing so we send the value using attribute on component and receive it in the child component by using @Input decorator for example of property binding see here -

<my-child [myProp]="myProp" />

Event Binding -

Catching the Child's Event/method from the parent component

whenever we have to fire some event on click or something else from child component and pass to the parent component, we have to use Event Binding see here in the example below -

<my-child [myProp]="myProp" (onPropChange)="onPropChange($event)" />

here we have onPropChange as output event binding, we can fire that event using EventEmitter.

for more detail see here

  • http://errietta.me/blog/angular2-property-event-binding/
  • https://www.patrickschadler.com/property-event-binding-angular-2/



回答2:


Line 1:

input [value]="username" (input)="username = $event.target.value"

Line 2:

Hello {{username}}!

Let’s take a closer look at what’s going on here:

  • [value]=”username” - Binds the expression username to the input element’s value property.
  • (input)=”expression” - Is a declarative way of binding an expression to the input element’s input event (yes there’s such event).
  • username = $event.target.value - The expression that gets executed when the input event is fired.
  • $event - Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.

Considering these observations, it becomes very clear what’s happening. We’re binding the value of the username expression to the input’s value property (data goes into the component).



来源:https://stackoverflow.com/questions/40188550/what-is-the-difference-between-event-binding-and-property-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!