Search code examples
javascriptangularangular4-forms

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>


Solution

    • 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)]