Craft

What Is Two-Way Binding in Angular?

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:

<input 
type="email"
id="email"
name="email"
placeholder="[email protected]"
[(ngModel)]="emailAddress"
/>

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;
    color:
    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;
    color:
    background:
    font-size: 20px;
    font-weight: 600;
    line-height: 28px;
    padding: 12px 20px;
    width: 100%;
    margin-top: 1rem;
    }

    .btn:hover {
    background:
    border:
    }

    .success {
    color:
    }

    .error {
    color:
    }

  5. Add the following CSS into src/styles.css to set the font family, background, and text colors of the overall app:
    @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400&display=swap");

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

  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>

    <form>
    <input
    type="text"
    id="username"
    name="username"
    placeholder="Please enter a username"
    />
    <button class="btn"> Save </button>
    </form>

    </div>
    </div>

  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';

    @NgModule({
    imports: [
    FormsModule
    ],
    })

  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.
    <input
    type="text"
    id="username"
    name="username"
    placeholder="Please enter a username"
    [(ngModel)]="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 {
    console.log(this.username);
    }
  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(
    this.username.toLowerCase()
    );

    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 }}
    </p>
  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.

[quads id=2]
Read the full article here

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button