Choose an option from the dropdown menu

I am facing a challenge with filtering data on a select element due to an overwhelming amount of options. Here is how I attempted to implement it:


  <mat-form-field>
    <mat-select placeholder="Unit.." (change)="onTabChange(element, $event.value.id, 'assignedUnit')">
      <input matInput type="text" (keyup)="filterListCareUnit($event.target.value)">
      <mat-option *ngFor="let careUnit of listCareUnits" [value]="careUnit">
        {{ careUnit.label }}
      </mat-option>
    </mat-select>
  </mat-form-field>

When the user types in a value,

filterListCareUnit($event.target.value)
function is called on key up event.

However, I am struggling with implementing the filter using RxJS in this function.

I have a collection named listCareUnits and my goal is to remove all objects that do not contain the value entered by the user ($event.target.value).

My current approach seems ineffective as the list remains unchanged. Here is my code snippet:


  filterListCareUnit(val) {
    console.log(val);
    this.listCareUnits.filter((unit) => unit.label.indexOf(val));
  }

As a newcomer to Angular/RxJS, any guidance or assistance would be greatly appreciated. Thank you!

Answer №1

Make sure to assign the filtered list that is returned.

 updateFilteredList(val) {
    console.log(val);
    this.filteredItems = this.filteredItems.filter((item) => item.label.indexOf(val) > -1);
  }

To avoid losing your original data array, it's recommended to create a separate array for processing that always contains the initial data set.

processingArray = this.filteredItems;
updateFilteredList(val) {
        console.log(val);
        this.filteredItems = this.processingArray.filter((item) => item.label.indexOf(val) > -1);
      }

Answer №2

Although the question has already been answered, an alternative solution could have been to utilize the "mat-select-filter" option.

https://www.npmjs.com/package/mat-select-filter

This information may prove useful to others in similar situations.

Answer №3

Here's a simple workaround that doesn't involve modifying the TypeScript file:

  <mat-select [(ngModel)]="result">
    <input matInput placeholder="filter.." #filterplc>
    <div  *ngFor="let opt of options ">
    <mat-option *ngIf="opt.includes(filterplc.value)"
                [value]="opt">
      {{opt}}
    </mat-option>
      </div>
  </mat-select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dependency injection in Angular is a powerful design pattern that

I recently completed an Angular 2 website, but I've run into some issues that I cannot seem to debug. I've spent the past week trying to find a solution but have had no luck. Below, I've included some snippets of my code. Feel free to ask fo ...

Creating a distinct input for each row in a table using Angular 2

I am encountering an issue with inputs being created for each row in my PrimeNG/datatable. The problem arises from the local variable #itsmIncident, which causes confusion when trying to pass values to the "Save" button as there are multiple rows involve ...

Setting up Typescript classes that inherit from one another with diverse properties for each subclass

I'm fairly new to Typescript and currently grappling with how to effectively manage class inheritance when base classes have distinct properties. Essentially, I have a base class where I aim to define shared functionality and a series of subclasses w ...

How can a fixed type value be assigned to a portion of a type that is constrained by generics?

Experience a new aspect of Ids with my basic interface: interface Identifiable { id?: number; } Behold, a universal function that transforms record objects into entities with ids: function transformRowToObject<T extends Identifiable>(row: { id: ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Developing a Gulp buildchain: Transforming Typescript with Babelify, Browserify, and Uglify

I've configured a buildchain in Gulp, but when I execute the gulp command, it only utilizes one of the two entry points I specify. My goal is to merge the methods outlined in these two resources: and here: https://gist.github.com/frasaleksander/4f7b ...

Clicking on the mat-icon-button with the matSuffix in the password field will always trigger a

Seeking assistance with implementing mat-icon-button matSuffix in Angular for a login page. This is my first time working with Angular and I am facing an issue with the password field. I have used mat-icon-button matSuffix, but whenever I click on the ico ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

The HTMLInputElemet type does not include a Property Rows

Hey there, I'm just starting to dive into Angular and TypeScript. My current challenge is figuring out how to check if a table is empty or not so that I can show or hide a specific div accordingly. I've attempted the following: var rows = docume ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

The evaluation of this statement will consistently yield 'false' due to the lack of overlap between the types 'Promise<number>' and '1'

I am attempting to modify the label from "pending" or "pendiente" to "pending-rejected" or "pendiente-rechazado". Even though this seems like a simple change, it is proving to be more complex than I anticipated. Below is the function I am using to retriev ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Can you explain the concept of a type object in typescript?

Can you explain the concept of the type object and its use? Some say it's like a blackbox. Which approach is better, A or B, when dealing with a parameter that may have unknown types of object keys? A const modifyData: (data: object) => void = da ...

I am looking to make changes to a user's profile

My goal is to only update the fields that I have specified, leaving other data unchanged. However, in my current situation, when I pass the key to be changed, all other fields are set to null. import userModel from '../../models/usermodel' impor ...

Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as: <about></about> <contact></contact> I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I a ...

The 'npm update' command seems to be failing when attempting to update dependencies within Angular2

I am looking to upgrade the outdated dependencies in my Angular 2 project. Upon running npm outdated, I identified several dependencies that need updating. However, when I attempt to update them using the npm update command, it does not seem to work as exp ...

What is the proper way to utilize the transform method in require('typescript')?

const babel = require('babel'); let sample = ` let greeting: string = 'hello, there'; ` babel.transform What is the method for changing strings within the provided code? ...

Angular component classes now use the updated RXJS 6.X syntax, rendering the previously used observable deprecated

Here is the component method I am using: if (id !== undefined && id != null && id !== 0) { this.dataService.getTransactionById(id).subscribe( (tr: ITransactionResponse) => { ...

Update optional parameter in Angular UIRouter without triggering a reload

I am currently working on an Angular 4 application with multiple routes (ui-router) that allow optional parameters. { name: 'shirts', url:'/shirts/:color/:size, component: ShirtComponent } While the current setup functions as intended, I a ...

What is the method for including a placeholder (instead of a label) in the MUI 5 DatePicker component?

I'm looking to customize the placeholder text in MUI 5's date picker. You can find the MUI 5 datepickerlink here: https://mui.com/x/react-date-pickers/date-picker/ The desired outcome:: I've tried referring to this chat, but it hasn't ...