ngx-modialog

ngx-modialog

June 09, 2018

ngx-modialog (previously `angular2-modal`)

This project is looking for a new maintainer, see [#414](https://github.com/shlomiassaf/ngx-modialog/issues/414) for details.

ngx-modialog version 5.x.x works with angular 5.x.x

IMPORTANT - V4 BREAKING CHANGE:

Version 4.x.x contains some breaking changes, please see the [CHANGELOG](./CHANGELOG.md)

Library has been renamed from version 3.0.2

Modal / Dialog implementation for angular. - Easy to use API via Fluent API Presets (alert, prompt, confirm) - Can render Component's, TemplateRef's and literal string - Extendable via plugins. - Easy to use typescript modal.alert() .title('Hello World') .body('In Angular') .open(); Available plugins: - Bootstrap (3 & 4) - [Vex 3 & 4](http://github.hubspot.com/vex/docs/welcome/)

Install

bash npm install ngx-modialog

Basic plunker playground (bootstrap plugin):

ngx-modialog @ 4.x.x

http://plnkr.co/edit/lV7zsw7Yqossgs9JOfQU?p=preview

ngx-modialog @ 3.x.x

http://plnkr.co/edit/2ppVYl517GI1Byv8vVbG?p=preview

Quick start

**In your application root module definition add `ModalModule` and the plugin you want to use:** We will use the bootstrap plugin (`BootstrapModalModule`) for this introduction. ```typescript import { ModalModule } from 'ngx-modialog'; import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap'; // lots of code... @NgModule({ bootstrap: [ /* ... */ ], declarations: [ /* ... */ ], imports: [ /* ... */ ModalModule.forRoot(), BootstrapModalModule ], }) export class AppModule { /* lots of code... */ } ```

In any angular component or service inject the `Modal` service and open a modal:

typescript import { Component, ViewContainerRef } from '@angular/core'; import { Overlay } from 'ngx-modialog'; import { Modal } from 'ngx-modialog/plugins/bootstrap'; @Component({ selector: 'my-app', template: `<button (click)="onClick()">Alert</button>` }) export class AppComponent { constructor(public modal: Modal) { } onClick() { const dialogRef = this.modal.alert() .size('lg') .showClose(true) .title('A simple Alert style modal window') .body(` <h4>Alert is a classic (title/body/footer) 1 button modal window that does not block.</h4> <b>Configuration:</b> <ul> <li>Non blocking (click anywhere outside to dismiss)</li> <li>Size large</li> <li>Dismissed with default keyboard key (ESC)</li> <li>Close wth button click</li> <li>HTML content</li> </ul>`) .open(); dialogRef.result .then( result => alert(`The result is: ${result}`) ); } } If you are using **ngx-modialog** version 3.X.X or below, `open()` returned a promise so replace the last 2 lines with: typescript dialogRef .then( dialogRef => { dialogRef.result.then( result => alert(`The result is: ${result}`); }); We are using the `alert()` method, one of 3 (prompt, confirm)) fluent-api methods we call `drop-ins` We then use the `result` property to wait for the modal closing event. **Notes:** - Fluent API methods (drop-ins) are pre-configured (presets) methods that allow easy configuration and execution, you can create custom presets - see the demo application. - For more control use the `open()` method, which is used by all drop in's internally. - We import the `Modal` service from the plugin and not from the root library. Import from the root should work but being explicit allow using multiple plugins. ## Demo App The Demo application is a full implementation of the library with the native plugins. View it at [shlomiassaf.github.io/ngx-modialog](http://shlomiassaf.github.io/ngx-modialog/) The demo application is [part of this repository](https://github.com/shlomiassaf/ngx-modialog/tree/master/src/demo/app) and it is a great place to learn by example.

Bootstrap / VEX features:

- Customizable with components, Presets and more... - Select cancel/quit key. - Cascading modals. - Element blocking. - Blocking / Non blocking modal. - Modal as a component, replace the content by supplying a custom component. The demo application comes with a [dynamic modal generator](http://shlomiassaf.github.io/ngx-modialog#/bootstrap-demo/customizeModals) for the **Boostrap** plugin ## Plugins Plugins serve as a concrete UI implementation for a modal. It can be an implementation for a known library (e.g: bootstrap) or something completely unique While `ngx-modialog` has some built in plugins it is also possible to use external plugins from NPM, if someone decide to build one. > Built a plugin? I would love to know :) # Known bugs ### The dialog closes when removing the target DOM element in a click event ref [issue#111](https://github.com/shlomiassaf/ngx-modialog/issues/111) To avoid this problem use `event.stopPropagation();` or put the element removal inside a `setTimeout` call # HELP WANTED! As a sole author I find it difficult to maintain multiple open source projects. As a result it is hard for me to replay rapidly to requests/help/etc... If you would like to contribute, please contact me, the community will thank you. You can contribute via: - Implementing features & Bug fixes - Documentation (Extremely important) - Issue management
ngSocketIO

ngSocketIO

February 22, 2018
Socket.IO module for AngularJS

Requirements

  • AngularJS 1.0.5+
  • Socket.IO 0.9.16

Installing

Simply download either ng-socket-io or ng-socket-io.min.js from the build folder and add it to your web application. Just make sure it's included after the AngularJS script.

Usage

  1. Add the socket-io module as a dependency in your AngularJS app;
  2. Inject the socket factory wherever you need to use Socket.IO;
  3. You're done!

Example

 <script src="angular.js"></script>  
 <script src="ng-socket-io.js"></script>  
 <script>  
   var myApp = angular.module('myApp', ['socket-io']);  
   myApp.controller('MyCtrl', function($scope, socket) {  
     // Listening to an event  
     socket.on('someEvent', function(data) {  
       $scope.data = data;  
     });  
     // Raising an event  
     $scope.raise = function(message) {        
       socket.emit('otherEvent', message);  
     };  
   });  
 </script>  

Cancelling a subscription automatically on scope destruction

If you want to unsubscribe from an event automatically on scope destruction, just call bindTo passing the current scope:
 socket.on('someEvent', function(data) {  
 ...   
 }).bindTo($scope);  

Note: Special thanks to Michael Benford
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
ngTagsInput

ngTagsInput

February 18, 2018
Tags input directive for AngularJS. Check out the ngTagsInput website for more information.

Requirements

  • AngularJS 1.3+
  • A modern browser (Chrome 31+, Firefox 29+, Safari 7+, Opera 12+, IE 10+)

Installing

All files are available from a variety of sources. Choose the one that best fits your needs:
You can also grab the latest build generated by Travis. It's fully functional and may contain new features and bugfixes not yet published to the services listed above.
Now all you have to do is add the scripts to your application. Just make sure the ng-tags-input.js file is inserted after the angular.js script:
 <script src="angular.js"></script>  
 <script src="ng-tags-input.js"></script>  
 <link rel="stylesheet" type="text/css" href="ng-tags-input.css">  

Usage

  1. Add the ngTagsInput module as a dependency in your AngularJS app;
  2. Add the custom element <tags-input> to the HTML file where you want to use an input tag control and bind it to a property of your model. That property, if it exists, must be an array of objects and each object must have a property named text containing the tag text;
  3. Set up the options that make sense to your application;
  4. Enable autocomplete, if you want to use it, by adding the directive <auto-complete> inside the <tags-input> tag, and bind it to a function of your model. That function must return either an array of objects or a promise that eventually resolves to an array of objects (same rule from step 2 applies here);
  5. Customize the CSS classes, if you want to.
  6. You're done!
Note: There's a more detailed getting started guide on the ngTagsInput website.

Example

 <html>  
 <head>  
   <script src="angular.min.js"></script>  
   <script src="ng-tags-input.min.js"></script>  
   <link rel="stylesheet" type="text/css" href="ng-tags-input.min.css">  
   <script>  
     angular.module('myApp', ['ngTagsInput'])  
       .controller('MyCtrl', function($scope, $http) {  
         $scope.tags = [  
           { text: 'just' },  
           { text: 'some' },  
           { text: 'cool' },  
           { text: 'tags' }  
         ];  
         $scope.loadTags = function(query) {  
            return $http.get('/tags?query=' + query);  
         };  
       });  
   </script>  
 </head>  
 <body ng-app="myApp" ng-controller="MyCtrl">  
   <tags-input ng-model="tags">  
     <auto-complete source="loadTags($query)"></auto-complete>  
   </tags-input>  
 </body>  
 </html>  

Options

Check out the documentation page for a detailed view of all available options.

Demo

You can see the directive in action in the demo page.

Contributing

Before posting an issue or sending a pull request, make sure to read the CONTRIBUTING file.

License

See the LICENSE file.

Changelog

See the CHANGELOG page.

Alternatives

The following are some alternatives to ngTagsInput you may want to check out:
  • angular-tags: Pure AngularJS tagging widget with typeahead support courtesy of ui-bootstrap
  • angular-tagger: Pure Angular autocomplete with tags, no jQuery
  • jsTag: Open source project for editing tags (aka tokenizer) based on AngularJS
  • bootstrap-tagsinput: jQuery plugin providing a Twitter Bootstrap user interface for managing tags (provides Angular support)

Latest build


Note: Special thanks to Michael Benford
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
textAngular

textAngular

February 15, 2018
A radically powerful Text-Editor/Wysiwyg editor for Angular.js! Create multiple editor instances, two-way-bind HTML content, watch editors for changes and more!

 

How to Use:

  1. Include textAngular.js in your project, alternatively grab all this code and throw it in your "directives.js" module file.
  2. Include textAngular in your main app module.
  3. Create an element of some kind. (div, whatever, doesn't matter)
  4. Add the text-angular directive to it.
  5. Add a text-angular-name="<YOUR TEXT EDITOR NAME>" directive to the element, as well.
  6. Create a textAngularOpts object and bind it to your local scope in the controller you want controlling textAngular It should look something like:
  1. If you want all editors to have individual settings: Proceed to 2. Otherwise go to 3.
  2. Create the textAngularEditors property manually (it will get created regardless, if you choose not to apply individual settings).
  3. Then add to it, a new property with the name of your editor you chose earlier. For instance, if it was "coolMonkeyMan" it will look like this:
  1. Globally inherited settings for each editor or individual settings? Either way you'll need to supply some options!

Global Options

html <STRING> the default html to show in the editor on load (also will be the property to watch for HTML changes!!!)
toolbar <ARRAY of OBJECTS> holds the toolbar items to configure, more on that later
disableStyle <BOOLEAN> disable all styles on this editor
theme <OBJECT of OBJECTS> holds the theme objects, more on that later

Setting up the Toolbar

Add tools to the toolbar like:

Note

If you want to use ultra-sweet icons in the menu (like I did in the example) make sure to include fontAwesome!
And then use the proper syntax for the titles i,e <i class='icon-<icon name>'></i>
Get it at: www.bootstrapcdn.com/#fontawesome

Toolbar Options

title <STRING> Can be an angular express, html, or text. Use this to add icons to each tool i,e <i class='icon-code'></i>
name <STRING> the command, the tool name, has to be one of the following: html <- this one is used to toggle the html view, so i'd probably keep it ;-) h1 h2 h3 p pre ul ol quote undo redo b justifyLeft justifyRight justifyCenter i clear insertImage insertHtml createLink 

Theming textAngular

Every piece of textAngular has a specific class you can grab and style in CSS. However, you can also use the theme object to specify styling. Each property takes a normal, jQuery-like CSS property object. Heres an example :

Theme Options

editor <OBJECT> the actual editor element
toolbar <OBJECT> the toolbar wrapper
toolbarItems <OBJECT> each toolbar item
insertForm <OBJECT> the form that holds the insert stuff
insertFormBtn <OBJECT> the button that submits the insert stuff

How to get the Editor Html

To actually get the model (watch or bind), simply follow this model:
textAngularOpts.textAngularEditors.<YOUR EDITORS NAME>.html
so to bind the expression:
or to $watch for changes:

Issues?

textAngular uses execCommand for the rich-text functionalty. That being said, its still a fairly experimental browser feature-set, and may not behave the same in all browsers. I've tested in FF, chrome and IE10 and its works as expected. If you find something, please let me know. Throw me a message, or submit a issue request!


Note: Special thanks to Austin Anderson
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
angular-loading-bar

angular-loading-bar

February 02, 2018
The idea is simple: Add a loading bar / progress bar whenever an XHR request goes out in angular. Multiple requests within the same time period get bundled together such that each response increments the progress bar by the appropriate amount.
This is mostly cool because you simply include it in your app, and it works. There's no complicated setup, and no need to maintain the state of the loading bar; it's all handled automatically by the interceptor.

Requirements: AngularJS 1.2+

File Size: 2.4Kb minified, 0.5Kb gzipped

Usage:

  1. include the loading bar as a dependency for your app. If you want animations, include ngAnimate as well. note: ngAnimate is optional
     angular.module('myApp', ['angular-loading-bar', 'ngAnimate'])  
    
  2. include the supplied JS and CSS file (or create your own CSS to override defaults).
     <link rel='stylesheet' href='build/loading-bar.min.css' type='text/css' media='all' />  
     <script type='text/javascript' src='build/loading-bar.min.js'></script>  
    
  3. That's it -- you're done!

via bower:

 $ bower install angular-loading-bar  

via npm:

 $ npm install angular-loading-bar  

via CDN:

  <link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/angular-loading-bar/0.9.0/loading-bar.min.css' type='text/css' media='all' />  
  <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular-loading-bar/0.9.0/loading-bar.min.js'></script>  

Why I created this

There are a couple projects similar to this out there, but none were ideal for me. All implementations I've seen require that you maintain state on behalf of the loading bar. In other words, you're setting the value of the loading/progress bar manually from potentially many different locations. This becomes complicated when you have a very large application with several services all making independent XHR requests. It becomes even more complicated if you want these services to be loosly coupled.
Additionally, Angular was created as a highly testable framework, so it pains me to see Angular modules without tests. That is not the case here as this loading bar ships with 100% code coverage.
Goals for this project:
  1. Make it automatic
  2. Unit tests, 100% coverage
  3. Must work well with ngAnimate
  4. Must be styled via external CSS (not inline)
  5. No jQuery dependencies

Configuration

Turn the spinner on or off:

The insertion of the spinner can be controlled through configuration. It's on by default, but if you'd like to turn it off, simply configure the service:
 angular.module('myApp', ['angular-loading-bar'])  
  .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {  
   cfpLoadingBarProvider.includeSpinner = false;  
  }])  

Turn the loading bar on or off:

Like the spinner configuration above, the loading bar can also be turned off for cases where you only want the spinner:
 angular.module('myApp', ['angular-loading-bar'])  
  .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {  
   cfpLoadingBarProvider.includeBar = false;  
  }])  

Customize the template:

If you'd like to replace the default HTML template you can configure it by providing inline HTML as a string:
 angular.module('myApp', ['angular-loading-bar'])  
  .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {  
   cfpLoadingBarProvider.spinnerTemplate = '<div><span class="fa fa-spinner">Loading...</div>';  
  }])  

Position the template:

If you'd like to position the loadingBar or spinner, provide a CSS selector to the element you'd like the template injected into. The default is the



element:
 angular.module('myApp', ['angular-loading-bar'])  
  .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {  
   cfpLoadingBarProvider.parentSelector = '#loading-bar-container';  
   cfpLoadingBarProvider.spinnerTemplate = '<div><span class="fa fa-spinner">Custom Loading Message...</div>';  
  }])  

 <div id="loading-bar-container"></div>  
Also keep in mind you'll likely want to change the CSS to reflect it's new position, so you'll need to override the default CSS:
 #loading-bar .bar {  
  position: relative;  
 }  

Latency Threshold

By default, the loading bar will only display after it has been waiting for a response for over 100ms. This helps keep things feeling snappy, and avoids the annoyingness of showing a loading bar every few seconds on really chatty applications. This threshold is totally configurable:
 angular.module('myApp', ['angular-loading-bar'])  
  .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {  
   cfpLoadingBarProvider.latencyThreshold = 500;  
  }])  

Ignoring particular XHR requests:

The loading bar can also be forced to ignore certain requests, for example, when long-polling or periodically sending debugging information back to the server.
 // ignore a particular $http GET:  
 $http.get('/status', {  
  ignoreLoadingBar: true  
 });  
 // ignore a particular $http POST. Note: POST and GET have different  
 // method signatures:  
 $http.post('/save', data, {  
  ignoreLoadingBar: true  
 });  

 // ignore particular $resource requests:  
 .factory('Restaurant', function($resource) {  
  return $resource('/api/restaurant/:id', {id: '@id'}, {  
   query: {  
    method: 'GET',  
    isArray: true,  
    ignoreLoadingBar: true  
   }  
  });  
 });  

How it works:

This library is split into two modules, an $http interceptor, and a service:

Interceptor
The interceptor simply listens for all outgoing XHR requests, and then instructs the loadingBar service to start, stop, and increment accordingly. There is no public API for the interceptor. It can be used stand-alone by including cfp.loadingBarInterceptor as a dependency for your module.

Service
The service is responsible for the presentation of the loading bar. It injects the loading bar into the DOM, adjusts the width whenever set() is called, and complete()s the whole show by removing the loading bar from the DOM.

Service API (advanced usage)

Under normal circumstances you won't need to use this. However, if you wish to use the loading bar without the interceptor, you can do that as well. Simply include the loading bar service as a dependency instead of the main angular-loading-bar module:

 angular.module('myApp', ['cfp.loadingBar'])  

 cfpLoadingBar.start();  
 // will insert the loading bar into the DOM, and display its progress at 1%.  
 // It will automatically call `inc()` repeatedly to give the illusion that the page load is progressing.  
 cfpLoadingBar.inc();  
 // increments the loading bar by a random amount.  
 // It is important to note that the auto incrementing will begin to slow down as  
 // the progress increases. This is to prevent the loading bar from appearing  
 // completed (or almost complete) before the XHR request has responded.  
 cfpLoadingBar.set(0.3) // Set the loading bar to 30%  
 cfpLoadingBar.status() // Returns the loading bar's progress.  
 // -> 0.3  
 cfpLoadingBar.complete()  
 // Set the loading bar's progress to 100%, and then remove it from the DOM.  

Events

The loading bar broadcasts the following events over $rootScope allowing further customization:

cfpLoadingBar:loading triggered upon each XHR request that is not already cached

cfpLoadingBar:loaded triggered each time an XHR request recieves a response (either successful or error)

cfpLoadingBar:started triggered once upon the first XHR request. Will trigger again if another request goes out after cfpLoadingBar:completed has triggered.

cfpLoadingBar:completed triggered once when the all XHR requests have returned (either successfully or not)

Credits:

Credit goes to rstacruz for his excellent nProgress.

Note: Special thanks to Wes Cruver
Contact: chieffancypants@gmail.com
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
angular-http-auth

angular-http-auth

February 01, 2018
This is the implementation of the concept described in Authentication in AngularJS (or similar) based application.
There are releases for both AngularJS 1.0.x and 1.2.x, see releases.
Launch demo here or switch to gh-pages branch for source code of the demo.

Usage

  • Install via bower: bower install --save angular-http-auth
  • ...or via npm: npm install --save angular-http-auth
  • Include as a dependency in your app: angular.module('myApp', ['http-auth-interceptor'])

Manual

This module installs $http interceptor and provides the authService.

The $http interceptor does the following: the configuration object (this is the requested URL, payload and parameters) of every HTTP 401 response is buffered and everytime it happens, the event:auth-loginRequired message is broadcasted from $rootScope.

The authService has only 2 methods: loginConfirmed() and loginCancelled().
You are responsible to invoke loginConfirmed() after user logs in. You may optionally pass in a data argument to this method which will be passed on to the loginConfirmed $broadcast. This may be useful, for example if you need to pass through details of the user that was logged in. The authService will then retry all the requests previously failed due to HTTP 401 response.
You are responsible to invoke loginCancelled() when authentication has been invalidated. You may optionally pass in a data argument to this method which will be passed on to the loginCancelled $broadcast. The authService will cancel all pending requests previously failed and buffered due to HTTP 401 response.
In the event that a requested resource returns an HTTP 403 response (i.e. the user is authenticated but not authorized to access the resource), the user's request is discarded and the event:auth-forbidden message is broadcast from $rootScope.

Ignoring the 401 interceptor

Sometimes you might not want the interceptor to intercept a request even if one returns 401 or 403. In a case like this you can add ignoreAuthModule: true to the request config. A common use case for this would be, for example, a login request which returns 401 if the login credentials are invalid.

Typical use case:

  • somewhere (some service or controller) the: $http(...).then(function(response) { do-something-with-response }) is invoked,
  • the response of that requests is a HTTP 401,
  • http-auth-interceptor captures the initial request and broadcasts event:auth-loginRequired,
  • your application intercepts this to e.g. show a login dialog:
  • DO NOT REDIRECT anywhere (you can hide your forms), just show login dialog
  • once your application figures out the authentication is OK, call: authService.loginConfirmed(),
  • your initial failed request will now be retried and when proper response is finally received, the function(response) {do-something-with-response} will fire,
  • your application will continue as nothing had happened.

Sending data to listeners:

You can supply additional data to observers across your application who are listening for event:auth-loginConfirmed and event:auth-loginCancelled:
  $scope.$on('event:auth-loginConfirmed', function(event, data){  
       $rootScope.isLoggedin = true;  
       $log.log(data)  
  });  
  $scope.$on('event:auth-loginCancelled', function(event, data){  
   $rootScope.isLoggedin = false;  
   $log.log(data)  
  });  
Use the authService.loginConfirmed([data]) and authService.loginCancelled([data]) methods to emit data with your login and logout events.

Updating $http(config):

Successful login means that the previous request are ready to be fired again, however now that login has occurred certain aspects of the previous requests might need to be modified on the fly. This is particularly important in a token based authentication scheme where an authorization token should be added to the header.
The loginConfirmed method supports the injection of an Updater function that will apply changes to the http config object.
 authService.loginConfirmed([data], [Updater-Function])  
 //application of tokens to previously fired requests:  
 var token = response.token;  
 authService.loginConfirmed('success', function(config){  
  config.headers["Authorization"] = token;  
  return config;  
 })  
The initial failed request will now be retried, all queued http requests will be recalculated using the Updater-Function.
It is also possible to stop specific request from being retried, by returning false from the Updater-Function:
 authService.loginConfirmed('success', function(config){  
  if (shouldSkipRetryOnSuccess(config))  
   return false;  
  return config;  
 })  

Note: Special thanks to Witold Szczerba
Contact: witoldsz.dev@gmail.com
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
angular2-multiselect-dropdown

angular2-multiselect-dropdown

December 25, 2017
Angular 2 multiselect dropdown component for web applications. Easy to integrate and use.

Table of Contents

1. Getting Started
2. Installation
3. Usage
4. Templates
5. Template Driven Forms support
6. Reactive Forms support
7. Settings configuration
8. Callbacks and events

Getting Started

Installation

  • The Mutiselect Dropdown package is published on the npm Registry.
  • Install the package : npm install angular2-multiselect-dropdown
  • Once installed import AngularMultiSelectModule from the installed package into your module as follows:

Usage

Import AngularMultiSelectModule into NgModule in app.module.ts
 import { AngularMultiSelectModule } from 'angular2-multiselect-dropdown/angular2-multiselect-dropdown';  
 @NgModule({  
  // ...  
  imports: [  
   AngularMultiSelectModule,  
  ]  
  // ...  
 })  
Declare the component data variables and options in your component where you want to consume the dropdown component.
 import { Component, OnInit } from '@angular/core';  
 export class AppComponent implements OnInit {  
   dropdownList = [];  
   selectedItems = [];  
   dropdownSettings = {};  
   ngOnInit(){  
     this.dropdownList = [  
                {"id":1,"itemName":"India"},  
                {"id":2,"itemName":"Singapore"},  
                {"id":3,"itemName":"Australia"},  
                {"id":4,"itemName":"Canada"},  
                {"id":5,"itemName":"South Korea"},  
                {"id":6,"itemName":"Germany"},  
                {"id":7,"itemName":"France"},  
                {"id":8,"itemName":"Russia"},  
                {"id":9,"itemName":"Italy"},  
                {"id":10,"itemName":"Sweden"}  
               ];  
     this.selectedItems = [  
                 {"id":2,"itemName":"Singapore"},  
                 {"id":3,"itemName":"Australia"},  
                 {"id":4,"itemName":"Canada"},  
                 {"id":5,"itemName":"South Korea"}  
               ];  
     this.dropdownSettings = {   
                  singleSelection: false,   
                  text:"Select Countries",  
                  selectAllText:'Select All',  
                  unSelectAllText:'UnSelect All',  
                  enableSearchFilter: true,  
                  classes:"myclass custom-class"  
                 };        
   }  
   onItemSelect(item:any){  
     console.log(item);  
     console.log(this.selectedItems);  
   }  
   OnItemDeSelect(item:any){  
     console.log(item);  
     console.log(this.selectedItems);  
   }  
   onSelectAll(items: any){  
     console.log(items);  
   }  
   onDeSelectAll(items: any){  
     console.log(items);  
   }  
 }  
Add the following component tag in you template
 <angular2-multiselect [data]="dropdownList" [(ngModel)]="selectedItems"   
   [settings]="dropdownSettings"   
   (onSelect)="onItemSelect($event)"   
   (onDeSelect)="OnItemDeSelect($event)"  
   (onSelectAll)="onSelectAll($event)"  
   (onDeSelectAll)="onDeSelectAll($event)"></angular2-multiselect>  

Template - For custom html of menu item

 <angular2-multiselect [data]="dropdownList" [(ngModel)]="selectedItems" [settings]="dropdownSettings">  
  <c-item>  
      <ng-template let-item="item">  
       <label style="color: #333;min-width: 150px;">{{item.itemName}}</label>  
       <img [src]="item.image" style="width: 30px; border: 1px solid #efefef;margin-right: 20px;" />  
       <label>Capital - {{item.capital}}</label>  
      </ng-template>  
  </c-item>    
 </angular2-multiselect>  

Template Driven Forms support

 <form (ngSubmit)="onSubmit()" #loginForm="ngForm" style="border: 1px solid #ccc; padding: 10px;">  
     <div class="form-group">  
       <label for="name">Skills</label>  
       <angular2-multiselect [data]="itemList" [(ngModel)]="formModel.skills"   
                  [settings]="settings"   
                  (onSelect)="onItemSelect($event)"  
                  (onDeSelect)="OnItemDeSelect($event)"   
                  (onSelectAll)="onSelectAll($event)"   
                  (onDeSelectAll)="onDeSelectAll($event)" name="skills">  
       </angular2-multiselect>  
     </div>  
 </form>  

 formModel = {  
     name: '',  
     email: 'ascasc@aa.com',  
     skills: [{ "id": 1, "itemName": "Angular" }]  
   };  

Reactive Forms support

 <form [formGroup]="userForm" novalidate style="border: 1px solid #ccc; padding: 10px;">  
     <div class="form-group">  
       <label for="name">Skills</label>  
       <angular2-multiselect [data]="itemList" [(ngModel)]="selectedItems"   
                  [settings]="settings"   
                  (onSelect)="onItemSelect($event)"  
                  (onDeSelect)="OnItemDeSelect($event)"   
                  (onSelectAll)="onSelectAll($event)"   
                  (onDeSelectAll)="onDeSelectAll($event)" formControlName="skills">  
       </angular2-multiselect>  
     </div>  
 </form>  

 userForm: FormGroup;  
 this.userForm = this.fb.group({  
       name: '',  
       email: ['', Validators.required],  
       skills: [[], Validators.required]  
     });  

Settings

The following list of settings are supported by the component. Configure the settings to meet your requirement.
Setting Type Description Default Value
singleSelection Boolean To set the dropdown for single item selection only. false
text String Text to be show in the dropdown, when no items are selected. 'Select'
enableCheckAll Boolean Enable the option to select all items in list false
selectAllText String Text to display as the label of select all option Select All
unSelectAllText String Text to display as the label of unSelect option UnSelect All
enableSearchFilter Boolean Enable filter option for the list. false
maxHeight Number Set maximum height of the dropdown list in px. 300
badgeShowLimit Number Limit the number of badges/items to show in the input field. If not set will show all selected. All
classes String Custom classes to the dropdown component. Classes are added to the dropdown selector tag. To add multiple classes, the value should be space separated class names. ''
limitSelection Number Limit the selection of number of items from the dropdown list. Once the limit is reached, all unselected items gets disabled. none
disabled Boolean Disable the dropdown false
searchPlaceholderText String Custom text for the search placeholder text. Default value would be 'Search' 'Search'
groupBy String Name of the field by which the list should be grouped. none
searchAutofocus Boolean Autofocus search input field true

Callback Methods

  • onSelect - Return the selected item on selection. Example : (onSelect)="onItemSelect($event)"
  • onDeSelect - Return the un-selected item on un-selecting. Example : (onDeSelect)="OnItemDeSelect($event)"
  • onSelectAll - Return the list of all selected items. Example : (onSelectAll)="onSelectAll($event)"
  • onDeSelectAll - Returns an empty array. Example : (onDeSelectAll)="onDeSelectAll($event)"
  • onOpen - Callback method fired after the dropdown opens Example : (onOpen)="onOpen($event)"
  • onClose - Callback method, fired when the dropdown is closed Example : (onClose)="onClose($event)"

Note: Special thanks to Pradeep Terli
Contact: solomon.terli@gmail.com
Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.