Articles in this section
Category / Section

Two-way databinding with ngModel

2 mins read

Angular provides us a directive ngModel to achieve two-way data binding. Two-way data-binding means that any data-related changes affecting the view-model are immediately propagated to the matching view(s), and vice-versa.

ngModel property comes with a property and event binding as well i.e. ngModel is bound to the controls with in the brackets ‘[()]’.

 Syncfusion Angular Components supports Two-way databinding with ngModel for input components like ejTextBox, ejDatePicker, ejTimePicker, etc,.

Refer to the below code snippet for ngModel in view file

<input type="text" ej-numerictextbox [(ngModel)]="value"/>

<h1>{{value}}</h1>

 

 

In our NumericTextBox Component, value property supports two-way binding with ngModel. Whatever the input will be given to the value property, will affect in view and model. The given input to value property will be append with the h1 tag through interpolation.

ngModel with Form

 

The input components are mainly used inside forms. The ngForm needs to import the FormsModule into our application’s root module.

In this Angular form, we are going to get the user inputs through ngModel property.

Refer to the below code snippet for view file.

<h2>Login Form</h2>

 

<form (ngSubmit)="onSubmit(loginForm.value)" #loginForm="ngForm">

    <div class="container">

        <label for="name"><b>Username</b></label>

        <input type="text" class="e-textbox" placeholder="Enter Username" name="name" required [(ngModel)]="username">

        <label for="password"><b>Password</b></label>

        <input type="password" class="e-textbox" placeholder="Enter Password" name="password" required [(ngModel)]="userpassword">

        <button type="submit" ej-button text="Login" (ejclick)="onclick($event)">Submit</button>

    </div>

</form>

In this model file, we are retrieving the username and userpassword in a button click event. As well as retrieving the inputs through form instance.

Refer to the below code snippet for model file.

import { Component } from '@angular/core';

 

@Component({

    selector: 'ej-app',

    templateUrl: './form.component.html',

    styleUrls: ['./form.component.css']

})

export class FormComponent {

    submitted: boolean;

    username: any;

    userpassword: any;

    constructor() { }

    onclick() {

        console.log(this.username); // Getting input values through ngModel property

        console.log(this.userpassword);

    }

    onSubmit(value: any) {

        console.log(value.name);

        console.log(value.password); // Getting input values through form instance

    }

}

 

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied