Categories

Thursday, April 25, 2024
#919814419350 therichposts@gmail.com
Angular 8Javascriptselect2

How to implement select2 in angular 8?

Angular playing api data

Hello guys, welcome to therichpost.com. In this post, I will tell you, How to Implement Select2 in Angular 8?

I was sitting and thinking and suddenly an Idea came to my mind and I wrote new post related select2 implementation in Angular 8.

Select2 is very well customize select box with searching, sorting, autocomplete and many more features.

Here is the working picture:

How to Implement Select2 in Angular 7?

Here are the working coding steps:

1. Very first, you need to run common below commands to add Angular 8 project on your machine:
$ npm install -g @angular/cli 

$ ng new angularselect2 //Install Angular Project

$ cd angularselect2 // Go to project folder

$ ng serve //Run Project

http://localhost:4200/ //Run On local server
2. Now you need to run below commands to add select2 and jquery into your Angular application:
npm install select2

npm install jquery --save
3. Now add below code into your angular.json file:
...
"styles": [
              "src/styles.css",
              "node_modules/select2/dist/css/select2.min.css", 
              "node_modules/select2/dist/js/select2.min.js" // I added here because this is not working in script block
          ],
"scripts":[
              "node_modules/jquery/dist/jquery.js"
          ]
...
4. Now add below code into your app.component.ts file:
import { Component, OnInit } from '@angular/core';
import * as jquery from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angularselect2';

  ngOnInit()
  {
       jquery('.js-example-basic-single').select2(); //initialize select2 to particular input
  }
}
5. Finally add below code into your app.component.html file:
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <select class="js-example-basic-single" name="state" style="width: 150px;">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
</div>

This is it. If you have any query related to this post then do comment below or you can ask questions.

Thank you,

Jassa,

TheRichPost.

Notes: I have this blog for helping others and everyone can ask me queries related to Angular, Laravel, WordPress etc. I will be very happy to help all.

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.