Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was the design decision taken to use differing brackets?

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.

like image 857
gazzwi86 Avatar asked Dec 05 '16 10:12

gazzwi86


2 Answers

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

like image 93
Suren Srapyan Avatar answered Nov 14 '22 23:11

Suren Srapyan


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.

like image 23
danday74 Avatar answered Nov 14 '22 23:11

danday74