Multiple Select Dropdown Using Angular With Tag
I am building up angular 6 application, in which i am in the need to make a multi select dropdown using text box without using
Solution 1:
Here is the working code, I used [(ngModel)] instead formcontrols:
https://stackblitz.com/edit/angular-qjrhs5?file=src%2Fapp%2Fapp.component.css
Solution 2:
Check this StackBlitz: Dropdown Example
HTML file:
<buttontype="button" (click)="clear()">Clear</button><divclass="autocomplete"><inputname="suggestion"type="text"placeholder="User" (click)="suggest()" [formControl]="typeahead"><divclass="autocomplete-items" *ngIf="show"><div *ngFor="let s of suggestions" (click)="selectSuggestion(s)">{{ s }}</div></div></div>
TS file:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export classAppComponent{
name = 'Angular';
suggestions: string [] = [];
suggestion: string;
show: boolean = false;
typeahead: FormControl = new FormControl();
fieldHistory: string [] = [];
suggest() {
this.suggestions = this.users;
this.show = true;
}
selectSuggestion(s) {
this.suggestion = "";
var index = this.fieldHistory.findIndex(function(element) {
return element === s;
});
if (index === -1) {
this.fieldHistory.push(s);
} else {
var firstPart = this.fieldHistory.slice(0, index);
var secondPart = this.fieldHistory.slice(++index);
this.fieldHistory = firstPart.concat(secondPart);
}
for (let i = 0; i < this.fieldHistory.length; i++)
this.suggestion = this.suggestion + " " + this.fieldHistory[i];
this.typeahead.patchValue(this.suggestion);
this.show = false;
}
clear() {
this.suggestion = "";
this.fieldHistory.pop();
for (let item of this.fieldHistory)
this.suggestion = this.suggestion + " " + item;
this.typeahead.patchValue(this.suggestion);
}
users = ['First User', 'Second User', 'Third User', 'Fourth User'];
}
CSS file:
.autocomplete {
position: relative;
width: 100%;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-radius: 4px;
margin-top: 15px;
top: 100%;
left: 0;
right: 0;
}
.autocomplete-itemsdiv {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-itemsdiv:hover {
background-color: #e9e9e9;
}
Also import the module: import { ReactiveFormsModule } from '@angular/forms';
Post a Comment for "Multiple Select Dropdown Using Angular With Tag"