I have just started learning Angular2, and was wondering why the developers decided to use various different wrapper in he html? For instance:
[(ngModel)]="some.property"
(click)="someMethod()"
[src]="some.property"
I'm sure there is a nice logical reason behind it, and I am aware that they're used for differing purposes, but at first glance it seems inconsistent and an unnecessary obstacle to overcome.
Each syntax has its own goal.
1) Event Binding
This is a one way binding from inner to outer component. Called as event
. The outer component will call the someMethod
when the click
event is triggered from the inner component, or from the current tag
.
(click)="someMethod()"
Example: Here button
's click handler calls the onClickMe()
function
@Component({
selector: 'click-me',
template: `
<button (click)="onClickMe()">Click me!</button>
{{clickMessage}}`
})
export class ClickMeComponent {
clickMessage = '';
onClickMe() {
this.clickMessage = 'You are my hero!';
}
}
2) One way data binding
This is a one way binding from the outer into inner. This will pass the some.property
to the src
property in the inner component
or tag
.
[src]="some.property"
Example. Here we bind to the innerText property the value of name
property
<h1 [innerText]="name"></h1>
or
<h1>{{ name }}</h1>
3) Two way data binding
And this is a two way binding from inner to outer and vice versa. This will do the two things.
[(ngModel)]="some.property"
Example: Here input
's value will be updated when username
will be updated. And aslo when we type another value into the input, the username
will be updated. So here you get two way data bindings. And under the hood with [(ngModel)] it creates one-way and event-bindings. This lines
<input [(ngModel)]="name">
<p>Hello {{ name }}!</p>
are equal to
<input [value]="name" (input)="name = $event.target.value">
<p>Hello {{ name }}!</p>
For a deep knowledge you can look up in the documentation
this relates to visibility and control of binding. square brackets is binding from parent to child.
normal brackets is binding child to parent using event callbacks
both is two way binding.
In angular1 I think there was a lot less control over directional binding.
you can bind from controller to view, etc. But I use the parent child component example for simplicity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With