BILAL AHMAD
BILAL AHMAD

Reputation: 712

What is the difference between three types of data binding directives : [val] , [(val)] , (val) in Angular4

Considering the code below, i am trying to understand the difference between three different ways to do data binding. Since i am new to angular4 i need some clarity regarding when to use what. e.g. to assign ngModel, [(ngModel)] is used. To assign disabled attribute, [disabled] is used. To assign ngSubmit handler, (ngSubmit) is used. It's hard to differentiate between each one of them.

<section class="sample-app-content">
    <h1>Template-driven Form Example:</h1>
    <form #f="ngForm" (ngSubmit)="onSubmitTemplateBased()">
        <p>
            <label>First Name:</label>
            <input type="text"  
                [(ngModel)]="user.firstName" required>
        </p>

        <p>
            <label>Password:</label>
            <input type="password"  
                [(ngModel)]="user.password" required>
        </p>
        <p>
            <button type="submit" [disabled]="!f.valid">Submit</button>
        </p>
    </form>
</section>

Upvotes: 0

Views: 118

Answers (2)

Ashraful Islam
Ashraful Islam

Reputation: 1263

  • Property Binding is denoted with [ ] Ex. [disabled] [src] [data]
  • Event Binding is denoted with () Ex. (click) (keypress) (hover)
  • Two way binding denoted with [()] as there is a property binding and an event binding happens behind the scene. [(ngModel)]

Upvotes: 1

Dmitry Sobolevsky
Dmitry Sobolevsky

Reputation: 1191

  1. Property binding [val]: One-way in People often describe property binding as one-way data binding because it flows a value in one direction, from a component's data property into a target element property.

You cannot use property binding to pull values out of the target element. You can't bind to a property of the target element to read it. You can only set it.

  1. Event binding (val):The bindings directives you've met so far flow data in one direction: from a component to an element.

Users don't just stare at the screen. They enter text into input boxes. They pick items from lists. They click buttons. Such user actions may result in a flow of data in the opposite direction: from an element to a component.

The only way to know about a user action is to listen for certain events such as keystrokes, mouse movements, clicks, and touches. You declare your interest in user actions through Angular event binding.

  1. Two-way binding [(val)]: You often want to both display a data property and update that property when the user makes changes.

On the element side that takes a combination of setting a specific element property and listening for an element change event.

Angular offers a special two-way data binding syntax for this purpose, [(x)]. The [(x)] syntax combines the brackets of property binding, [x], with the parentheses of event binding, (x).

Upvotes: 3

Related Questions