Create a new Angular project
Using Ng CLI tool we will create a new Angular project by running below command in terminal:
$ ng new ng-select-demo
Install & Configure
ng-select
After creating an Angular project next we will install ng-select page.
Step 1) Run the following command in terminal to install ng-select:
$ npm install --save @ng-select/ng-select
Step 2) To use ng-select component, we need to import NgSelectModule
& FormsModule
in app.module.ts file:
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgSelectModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 3) Finally, add a theme to style our awesome ng-select component.
We already have three themes available to select from. Import any of the following in the style.css file:
Use ng-select Component
To create a select component add the
ng-select
component as shown below:
<ng-select [items]="items"
bindLabel="name"
placeholder="Select item"
appendTo="body"
multiple="true"
[(ngModel)]="selected">
</ng-select>
with component class content: // app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
items = [
{id: 1, name: 'Python'},
{id: 2, name: 'Node Js'},
{id: 3, name: 'Java'},
{id: 4, name: 'PHP', disabled: true},
{id: 5, name: 'Django'},
{id: 6, name: 'Angular'},
{id: 7, name: 'Vue'},
{id: 8, name: 'ReactJs'},
];
selected = [
{id: 2, name: 'Node Js'},
{id: 8, name: 'ReactJs'}
];
}
There are some required and optional properties:
items: Array or object of local or remote content to populate as select options.
bindLabel: The property of object which we want to show as a label in select box.
placeholder: Text shown to the user when nothing is selected.
appendTo: By default, the options wrapper is appended to the ng-select element but it can be added to other elements using this property.
multiple: Single or multiple options can be selected by setting true or false
Great work bro... thanks a lot
ReplyDelete