Home Craft What Is Two-Way Binding in Angular?

What Is Two-Way Binding in Angular?

by Staff
0 comment

With two-way binding, your components can share data, handle events, and update values in real-time.

Two-way binding allows users to input data from the HTML file and send it to the TypeScript file and back. This is useful for input validation, manipulation, and more.

Once you pass data from the HTML to the TypeScript file, you can use the data to complete certain business logic. An example scenario would be if you wanted to check if the name entered into an input field already existed.

How Can You Use Two-Way Binding?

Two-way binding in Angular apps is usually set in the .html file, using the ngModel directive. Two-way binding in an input form can look something like this:

placeholder="[email protected]"

In the .ts file, the emailAddress variable is bound to the emailAddress from the form.

emailAddress: String = ''; 

How to Set Up an Example Form in an Angular App

By building a basic app, you can use two-way binding to check whether a potential username already exists.

  1. Create a new Angular app.
  2. Run the ng generate component command to create a new component. This is where you will store the form.
    ng generate component username-checker-form
  3. Replace all the code in your app.component.html file with the following tags:
    <app-username-checker-form> </app-username-checker-form>
  4. Add the following CSS into your new component’s .css file, located at username-checker-form.component.css, to style the form:
    .container {
    display: flex;
    text-align: center;
    justify-content: center;
    align-items: center;
    height: 100vh;

    .card {
    width: 50%;
    background-color: peachpuff;
    border-radius: 1rem;
    padding: 1rem;

    input {
    border: 3px solid
    border-radius: 5px;
    height: 50px;
    line-height: normal;
    display: block;
    width: 100%;
    box-sizing: border-box;
    user-select: auto;
    font-size: 16px;
    padding: 0 6px;
    padding-left: 12px;

    input:focus {
    border: 3px solid

    .btn {
    display: block;
    outline: 0;
    cursor: pointer;
    border: 2px solid
    border-radius: 3px;
    font-size: 20px;
    font-weight: 600;
    line-height: 28px;
    padding: 12px 20px;
    width: 100%;
    margin-top: 1rem;

    .btn:hover {

    .success {

    .error {

  5. Add the following CSS into src/styles.css to set the font family, background, and text colors of the overall app:
    @import url("[email protected];400&display=swap");

    body {
    font-family: "Poppins";
    background-color: papayawhip;

  6. Replace the code in username-checker-form.component.html, to add the username checker form:
    <div class="container">
    <div class="card">
    <h1> Username Checker </h1>

    placeholder="Please enter a username"
    <button class="btn"> Save </button>


  7. Run your app using the ng serve command in the terminal.
    ng serve
  8. View your application at http://localhost:4200/.

Sending Data Between the HTML and TypeScript Files

Use two-way binding to send data to your .ts file and back to the .html file. This is possible with the use of ngModel in the form’s input tags.

  1. Import the FormsModule into the app.module.ts file, and add it to the imports array:
    import { FormsModule } from '@angular/forms';

    imports: [

  2. Declare a username class variable in the .ts file, username-checker-form.component.ts:
    username: string = '';
  3. In username-checker-form.component.html, add [(ngModel)] with the username variable in the input tag. This enables two-way binding, and anything typed into the form’s username input gets assigned to the username variable in the .ts file.
    placeholder="Please enter a username"
  4. To test that data is being sent to the .ts file, create a save() method in username-checker-form.component.ts. When you submit the form, the application will call this function.
    save(): void {
  5. Add the ngSubmit directive to the <form> tags in username-checker-form.component.html, and call the save() method.
    <form (ngSubmit)="save()">
  6. When clicking on the Save button, the save() function will print the value entered into the input field to the console. You can view the console at runtime using the browser’s developer tools. If you are unfamiliar with browser DevTools or viewing the console, you can learn more about how to use Chrome DevTools.
  7. Send the username back to the .html file. Add the username variable between curly brackets to the username-checker-form.component.html file, after the <form> tags. Use curly brackets to display the value stored in the username variable.
    <h2 *ngIf="username"> Username entered: {{ username }} </h2>

    The form should show the data entered concurrently.

  8. In username-checker-form.component.ts, add some class variables to check if the username already exists. Declare a usernames array with a few taken usernames, and add a message string that informs the user of the check. The variable isValidUsername is true if the username entered is not in the usernames array.
    usernames: string[] = [ 'bart', 'lisa', 'fry', 'leela' ];
    message: string = '';
    isValidUsername: boolean = false;
  9. The save() method should check whether the username entered is already in the existing usernames array or not. Depending on the outcome, the message will be set accordingly.
    save(): void {
    if (this.username != '') {
    this.isValidUsername = !this.usernames.includes(

    if (this.isValidUsername) {
    this.message = `Your new username is '${this.username}'`;
    } else {
    this.message = `The username '${this.username}' has already been taken`;

  10. Complete the username-checker-form.component.html file by showing if the entered username exists or not. Add an error message underneath the <h2> tags after the form. The isValidUsername variable is helpful here to determine the color of the message displayed.
    <p *ngIf="username" [ngClass]="isValidUsername ? 'success' : 'error'">
    {{ message }}
  11. In your browser at localhost:4200, attempt to enter a username that exists in the usernames array: Then, attempt to enter a username that does not.

Using Two-Way Binding to Send Data When Developing an Application

Two-way binding is useful for validation, checks, calculations, and more. It allows components to communicate and share data in real-time.

You can use features of two-way binding in various parts of an app. Once you receive the data from the user, you can execute business logic and inform the user of the results.

Sometimes, you’d want to store the user’s data in a database. You can explore different types of database providers you can use, including the Firebase NoSQL Database.

Read the full article here

SaleBestseller No. 1
Apple AirPods Max Wireless Over-Ear Headphones. Active Noise Cancelling, Transparency Mode, Spatial Audio, Digital Crown for Volume Control. Bluetooth Headphones for iPhone - Green
Apple AirPods Max Wireless Over-Ear Headphones. Active Noise Cancelling, Transparency Mode, Spatial Audio, Digital Crown for Volume Control. Bluetooth Headphones for iPhone - Green
 Apple-designed dynamic driver provides high-fidelity audio; Active Noise Cancellation blocks outside noise, so you can immerse yourself in music
Bestseller No. 3
Apple iPad Air 2, 64 GB, Space Gray (Renewed)
Apple iPad Air 2, 64 GB, Space Gray (Renewed)
Apple iOS 8; 9.7-Inch Retina Display; 2048x1536 Resolution; A8X Chip with 64-bit Architecture; M8 Motion Coprocessor
SaleBestseller No. 4
2021 Apple 10.2-inch iPad (Wi-Fi, 64GB) - Silver
2021 Apple 10.2-inch iPad (Wi-Fi, 64GB) - Silver
Gorgeous 10.2-inch Retina display with True Tone; A13 Bionic chip with Neural Engine; 8MP Wide back camera, 12MP Ultra Wide front camera with Center Stage
Bestseller No. 5
2022 Apple TV 4K Wi‑Fi with 64GB Storage (3rd Generation)
2022 Apple TV 4K Wi‑Fi with 64GB Storage (3rd Generation)
4K Dolby Vision and HDR10+ for vivid picture quality; Dolby Atmos for three-dimensional, theater-like sound
Bestseller No. 7
Apple AirTag 4 Pack
Apple AirTag 4 Pack
Keep track of and find your items alongside friends and devices in the Find My app; Simple one-tap setup instantly connects AirTag with your iPhone or iPad
Bestseller No. 8
Apple MacBook Air with Intel Core i5, 1.6GHz, (13-inch, 4GB,128GB SSD) - Silver (Renewed)
Apple MacBook Air with Intel Core i5, 1.6GHz, (13-inch, 4GB,128GB SSD) - Silver (Renewed)
1.6 GHz dual-core Intel Core i5 (Turbo Boost up to 2.7 GHz) with 3 MB shared L3 cache; 13.3-Inch (diagonal) LED-backlit Glossy Widescreen Display, 1440 x 900 resolution
Bestseller No. 9
Apple Of My Eye
Apple Of My Eye
Amazon Prime Video (Video on Demand); Amy Smart, Burt Reynolds, Liam McIntyre (Actors); Castille Landon (Director) - Castille Landon (Writer) - Dori A. Rath (Producer)
SaleBestseller No. 10
Apple 35W Dual USB-C Port Compact Power Adapter ​​​​​​​
Apple 35W Dual USB-C Port Compact Power Adapter ​​​​​​​
The compact size and folding prongs make it easy to pack and store.; Charging cable sold separately.

You may also like

Leave a Comment

Iman Hearts is one of the biggest lifestyle news and articles portals, we provide the latest news and articles about family, lifestyle, entertainment, and many more, follow us to get the latest news about what matters to you.


© 2022 Iman Hearts. All rights reserved. Sitemap