Filter/search from the drop-down list of options using angular
Try like this:
options = [
{ value: "Small", selected: false },
{ value: "Medium", selected: false },
{ value: "Large", selected: false }
];
selectedUser: any;
filterdOptions = [];
filterUsers() {
this.filterdOptions = this.options.filter(
item => item.value.toLowerCase().includes(this.selectedUser.toLowerCase())
);
console.log(this.filterdOptions);
}
Demo
If you start typing sm
, the filtered option will show the object with value Small
Angular - choose more options from a drop-down list with filter
As you're changing the range of employees when you query, the filteredEmployeeOptions
reduces and the checkedEmployees
bases itself on this new reduced array. So, to keep the already selected employees, you'll have to store them into this new array.
But in order to do that, you'll need to have a property ( I assumed id
) that is going to help us preventing duplicates.
Try doing the following to see if it works:
filterItem(event) {
if(!event)
this.filteredEmployeeOptions = this.employeeOptions;
// when nothing has typed*/
else if (typeof event === 'string')
this.filteredEmployeeOptions = this.employeeOptions
.filter(employee =>
employee.firstName.toLowerCase()
.startsWith(event.toLowerCase()) || employee.lastName.toLowerCase()
.startsWith(event.toLowerCase()))
// now we are keeping the already checkedEmployees
.concat(this.checkedEmployees)
// and then we filter by the id to prevent duplicates
.filter(({ id }, index, newArr) => newArr.findIndex(elm => elm.id === id) === index);
}
How to add a search filter to a select option in angular
If you want to filter your array menaces
by typing on the first letter, then it is possible to filter your array like this:
HTML:
<select class="form-control"
(change)="mnVuln?.menaceActif?.menace.id = $event.target.value;
updateMenaceProcessus();
filterMenaces($event)">
<option></option>
<option *ngFor="let menace of menaces"
[value]="menace.id"
[selected]="menace.id === mnVuln?.menaceActif?.menace.id">
{{menace.nom}}</option>
</select>
TypeScript:
origMenaces = [];
methodAPIToGetMenaces() {
this.yourService()
.subscribe(s=> {
this.menaces = s;
this.origMenaces = s;
});
}
filterMenaces(str: string) {
if (typeof str === 'string') {
this.menaces = this.origMenaces.filter(a => a.toLowerCase()
.startsWith(str.toLowerCase()));
}
}
UPDATE 1:
If you want to filter by input
value:
HTML:
<input type="text"
(ngModelChange)="filterItem($event)"
[(ngModel)]="filterText">
<br>
<select
#selectList
[(ngModel)]="myDropDown"
(ngModelChange)="onChangeofOptions($event)">
<option value="empty"></option>
<option *ngFor="let item of items">
{{item}}
</option>
</select>
<p>items {{ items | json }}</p>
TypeScript:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 4';
myDropDown : string;
items = ['one', 'two', 'three'];
origItems = ['one', 'two', 'three'];
@ViewChild('selectList', { static: false }) selectList: ElementRef;
onChangeofOptions(newGov) {
console.log(newGov);
}
filterItem(event){
if(!event){
this.items = this.origItems;
} // when nothing has typed*/
if (typeof event === 'string') {
console.log(event);
this.items = this.origItems.filter(a => a.toLowerCase()
.startsWith(event.toLowerCase()));
}
console.log(this.items.length);
this.selectList.nativeElement.size = this.items.length + 1 ;
}
}
Please, see work example at stackblitz
Angular filtering with dropdown
Set ngModel
to get selected value and change
event to update the list:
<select [(ngModel)]="selectedBrand" (change)="valueSelected()">
<option *ngFor="let item of brandName">{{ item }}</option>
</select>
Then filtering items in the component when value has been changed:
public selectedBrand;
public valueSelected() {
this.goods = this.goodsService.goods.filter(item => item.name === this.selectedBrand);
}
Demo
Angular - Filter array of object using multiple dropdown seleted
Just invoke the correct logic based on whether filter.value
is an array or not.
This should work:
const results = this.gridValueClone.filter(data =>
arrFilter.every(filter =>
Array.isArray(filter.value)
? filter.value.includes(data[filter.field])
: filter.value === data[filter.field]
)
);
Your usage of forEach()
in the filter callback is a little wonky so I got rid of that and replaced it with a call to every()
.
Angular 12 - Select dropdown option based on the value in template
Previous solution doesn't work (at least, not worked in my test).
I did my try and you can test that it works in here
EXTRACT:
import { Component, OnInit } from "@angular/core";
interface CategoryInterface {
id: string;
name: string;
}
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
title = "Juan Berzosa select of an object value of a HTML select component solution";
prtl = {
name: "Stock Market",
id: 10,
category: {
id: "2",
name: "Football"
}
};
categories: CategoryInterface[];
selectedCategory: CategoryInterface;
constructor() {
this.categories = [
{
id: "1",
name: "Cricket"
},
{
id: "2",
name: "Football"
}
];
const selectedCategoryArray = this.categories.filter(
(itemCategory) =>
this.prtl.category.id === itemCategory.id &&
this.prtl.category.name === itemCategory.name
);
this.selectedCategory = selectedCategoryArray[0];
}
}
HTML:
<div>
<h1>
Welcome to {{ title }}!
</h1>
</div>
<!-- Portal Category -->
<div class="row prtl_field_margin">
<div class="col-4 prtl_form_field_right">
<label for="pCategory" class="control-label prtl_form_label"
>Category</label
>
</div>
<div class="col-4">
<select
class="form-control"
id="pCategory"
name="pCategory"
[(ngModel)]="selectedCategory"
>
<option value="" disabled>Choose a Category</option>
<option *ngFor="let c of categories" [ngValue]="c">{{ c.name }}</option>
</select>
</div>
<div class="col-4"></div>
</div>
P.S: As @arun-s said, don't forget to add the FormsModule in app.module.ts:
...
import { FormsModule } from "@angular/forms";
...
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
FormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Multiple drop down search filter angular
I hope i understdood you , here you are.
var data = [{ "caregory": "Electronics", "products": [{ "product": "PC", "description": "Item4 Product Page", "price": 99.99 }, { "product": "TV", "description": "lorem ipsum possum", "price": 250.00 }]}, { "caregory": "Home Design", "products": [{ "product": "Paintings", "description": "awesome description about anything", "price": 200.00 }, { "product": "Pencils", "description": "we are filters", "price": 29.99 }, { "product": "Sharpies", "description": "loremloremlorem", "price": 89.00 }]}];
var app = angular.module('app', ['angular.filter']);
var Controller = function() {
this.selected = {}; this.data = data; var self = this; this.search = function(predicate) { self.searchPredicate = predicate; }}
app.controller('ctrl', Controller);
<body ng-app="app" ng-controller="ctrl as vm"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.js"></script> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <div class="jumbotron"> <h1>Search engine</h1>
</div> <form> <div class="form-group"> <label for="caregory">Category</label> <select id="caregory" data-ng-model="vm.selected.category" ng-options="option as option.caregory for option in vm.data | orderBy:'caregory'"> <option value="">None</option> </select> <br /> <br /> <label for="filters">Product type</label> <select id="filters" ng-model="vm.selected.type" ng-options="option as option.product for option in vm.selected.category.products | unique: 'product'"> <option value="">None</option> </select> <br> <br> <label for="filters">Price</label> <select id="filters" ng-model="vm.selected.price" ng-options="option as option.price for option in vm.selected.category.products | unique: 'price'"> <option value="">None</option> </select> </div> <div class="form-group" ng-if="vm.selected.price"> <button class="btn btn-primary" ng-click="vm.search(vm.selected.price)">Search</button> </div> <div ng-if="vm.searchPredicate"> Searching for <b>{{vm.searchPredicate.product}}</b> in <b>{{vm.searchPredicate.description}}</b> with price <b>{{vm.searchPredicate.price | currency}}</b> </div> </form>
</body>
Related Topics
React Button Onclick Redirect Page
How to Apply the Length Condition on the Existing Regular Expression
How to Only Trigger Parent Click Event When a Child Is Clicked
Dynamically Change Background Color on Scroll
Jquery, Line Break in Textarea.. Don't Get \N and Get ↵
Node.Js Call Function If Button Clicked
Reactjs and Images in Public Folder
Json Object Array Inside Array Find and Replace in JavaScript
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
How to Hide Source Code and Inspect Element Via JavaScript or Jquery
How to Show Which Question a User Is on When Taking My Quiz
How to Reset the Bootstrap Modal When It Gets Closed and Open It Fresh Again
How to Open a File/Browse Dialog Using JavaScript
Save State When Refresh Page - Reactjs
Show/Hide Select Options Based on Value of Another Select Using Javascript/Jquery
How to Open a Url Link from JavaScript Inside a Google Apps Script HTML Google Site Gadget