jQuery Integration With Angular

In this article we will learn how to integrate jQuery in Angular

Angular is open source TypeScript framework with which we can build SPAs (single page applications),
Whereas Jquery is a javascript library that is easy to use.

There are some situations while developing angular applications jQuery can be used to make developing easy and jQuery makes code reduceable functionality.
Suppose when you are building a shopping website, in this, there is a button with this you have to submit form fields, after button click we can be done this process with using jQuery and also using Angular.

Step 1: Install jQuery by adding this code in cmd,

npm install jquery --save

 Include the Below line in the scripts section of angular.json 

"./node_modules/jquery/dist/jquery.min.js"

Declare global variable in app.component.ts after import

declare var jQuery: any;

Now we can use ids to get the data from the form and submit the form.

We will perform an example using jQuery Angular, For this follow below steps

Step 2:  After creating a new project, Paste this below code in  app.component.html

<div class="jumbotron">
  <div class="container">
    <form action="/action_page.php">
      <div class="form-group">
        <label for="firstName">First Name:</label>&nbsp;&nbsp;
        <input type="text" id="firstName" class="form-control">
      </div>
      <div class="form-group">
        <label for="lastName">Last Name:</label> &nbsp;&nbsp;
        <input type="text" class="form-control" id="lastName">
      </div><br>
      <button type="button" (click)="onSubmit()" class="btn btn-primary">Submit</button>
    </form>
    <div class="displayboard">
      <div>
        <h3>First Name:</h3>
        <span id="fn"></span>
      </div>
      <div>
        <h3>Last Name:</h3>
        <span id="ln"></span>
      </div>
    </div>
  </div>
</div>
<router-outlet></router-outlet>

Here I created an HTML form in this after filling all fields on the button click the values will be displayed in another div which has “displayboard” id

Step 3:  In app.component.ts paste the below code.

onSubmit() {
    const firstName = $('#firstName').val();
    const lastName = $('#lastName').val();

    $("#fn").text(firstName);
    $("#ln").text(lastName);
  }

On button submit onSubmit() function will be called, in this function, we will retrieve input fields and print those fields in displayboard by setting text values by using jQuery.

Run your project and see the output.

 

 

 

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories