How to effectively sort through users in Angular 6 without the need for a custom pipe

I am looking to customize the user.component template by implementing a filter functionality that will display only the users in the array that match the string entered in the text input field. Is there a way to bind the input value to the view without relying on a custom pipe since using the 'filter' pipe is no longer an option in Angular 6?

If I opt for [(ngModel)] two-way binding directive, how can I filter the string passed into it within my component without requiring a custom pipe?

Below is the users.component.html template:

<div class="wrapper">
  <span id = "search-box"><input class = "col-lg-7" id= "search-input" type="text"  name="users" placeholder = "Search by name"></span>
  <span id= "people">{{users.length}} <span *ngIf = "users.length == 1">Person</span><span *ngIf = "users.length > 1">People</span></span>
  <div class="accordion" id="accordionExample">
  <div class="card" *ngFor = "let user of users">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" [attr.data-target]="'#' + user" aria-expanded="true" aria-controls="collapseOne">
          {{user}}
        </button>
      </h5>
    </div>
      <div [attr.id]= "user" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
       <div class="card-body">
        <img src="./assets/user.jpg" id= "user-pic">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div><!-- end of .card -->
 </div><!--end of .accordion-->
</div><!--end of .wrapper -->

And here is the users.component.ts file:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit { 

 users: any[] = [
    "Bob",
    "James",
    "Mary"
  ];

  constructor() { }

  ngOnInit() {
  }
}

If utilizing a custom pipe becomes necessary, please provide instructions on setting this up.

Answer №1

If you want to achieve this, utilize the (input) method and make sure to filter your array when the input changes. It's recommended to use the prototype pattern to maintain a separate copy of your array. To see an example of how it's done, check out this link on StackBlitz: StackBlitz link

Answer №2

To avoid using the pipe, you have the option to achieve the same result within the ts file. Instead of utilizing the array variable in the html, consider using a function that will provide the filtered outcome.

An example demonstration can be found at this link - https://stackblitz.com/edit/angular-shghzh

Answer №3

I don't see why you're mentioning custom pipes or anything like that. The best solution, in my opinion, would be: 1. Create a new array named filteredUsers: any[] to be used in your view. 2. Then, add the following code to your template:

   <input class="col-lg-7"
    id="search-input"
    type="text" name="users"
    placeholder="Search by name"
    (onModelChange)='filterArray($event)'>

and update the array in your ngFor loop.

<div class="card" *ngFor="let user of filteredUsers">
  1. Create a function in your template.

filterArray(event){
   this.filteredUsers =  this.users.filter(user => user === event);
 }

In your HTML:

<div class="card" *ngFor="let user of filteredUsers">>

This should work perfectly fine for you.

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

What is the most effective method for detecting the conclusion of a wheel event in JavaScript?

Is there a way to trigger an event once my wheel event has finished? I came across a solution that uses a scroll event (which is similar) with a setTimeout function here: However, I'm curious if there's a more elegant method to detect when my w ...

Comparing Angular2 and Webpack: Choosing between i18n plugin or ng2-translate

Looking to develop a web application using Angular2 and bundling it with webpack. What is the most effective method for incorporating multiple languages? Option 1: i18n-plugin - Check it out here or Option 2: ng2-translate - Find more information here ...

Retrieving object information in the constructor using Angular and Typescript

When attempting to access an object's data within a constructor, it results in an "undefined" object. Even though it functions properly in the ngOnInit() function, the data which is about to be reset is required every time the component is initiated. ...

Encountered an issue while trying to access a property that is undefined in the

How can I extract data from a dropdown menu and display it in a text box? For instance, if a user selects an ID from the dropdown, I want to show the corresponding name in the textbox. I hope this explanation is clear and properly conveyed, as my English s ...

Discover the step-by-step process for moving data between collections in MongoDB

I am currently working on nestjs and have two collections, one for orders and the other for payments. My goal is to retrieve a single entry from the orders collection and save that same entry into the payments collection. Below is the code for the service ...

"Conceal Digits with SweetAlert2's Number Mask

Could you assist me in adding a number mask to an input field in sweetalert2? Here is my code: onClick(btn) { let code2_fa = ''; if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) { swal({ ...

What is the best way to troubleshoot issues in Visual Studio when using Angular, Firebase, and Chrome that result in a "Browser or

I'm currently using Visual Studio for debugging an Angular application that requires authentication through Firebase. I have successfully installed the "Debugger for Chrome" and everything is running smoothly until I need to log in, which authenticate ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

What factors does mongo consider when serializing an object?

I recently started working with BigNumbers from the bignumber.js package As I delve into Mongo, I find myself pondering how Mongo manages to serialize objects correctly, such as the BigNumbers. In my case, I have encountered a puzzling situation where two ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

Unleashing the Potential of a Single Node Express Server: Hosting Dual Angular Apps with Distinct Path

I have successfully managed to host two separate angular applications (one for customers and one for company staff) on the same node server, under different paths. The setup looks like this: // Serve admin app app.use(express.static(path.resolve(__dirname, ...

Arrange objects in dropdown menu to line up

I'm currently working on a dropdown menu and I have a specific requirement – the menu should always be split into two columns and be able to span multiple lines. However, I've encountered an issue where the columns are not aligned properly, cau ...

The TypeScript compiler does not transpile the .at() function

While converting TypeScript to JavaScript compatible with NodeJS v14 using the provided configuration: { "compilerOptions": { "lib": ["es2020"], "rootDir": "src", "outDir": "bui ...

Leveraging the ReturnType from a method within a Child class that inherits from an abstract class

I'm encountering an issue where TypeScript is throwing a lot of errors when trying to utilize the ReturnType of a method from an abstract class in a child class. Here's a simple example that illustrates the problem: Thank you abstract class Par ...

Ways to change props in a Vue component

One of my goals is to develop a custom checkbox using Vue. The idea is to utilize two icons from fontawesome - one for a locked state and the other for an unlocked state. Essentially, I want the icon to be locked when the checkbox is checked, and unlocked ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

The Ultimate Guide to Converting Enums to Object Types using Typescript

Imagine having an enum declared as follows: enum CustomerType { New = 'new', Owner = 'self', Loyal = 'subscriber' } Utilizing this enum can simplify checks like: if(customer.type === CustomerType.New) What is the re ...

Angular2 Eclipse: Eclipse Oxygen's HTML editor detects TypeScript errors in real-time

After installing the Eclipse Oxygen plugin for Angular2, I created a project using the Angular CLI and opened it in Eclipse. However, when trying to convert the project to an Angular project, I couldn't find the option under configuration. Instead, th ...

Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent: <div [my-component]="'text'"></div> Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>). However, for customization purposes, a user mig ...

Is there anyone out there who has integrated Leaflet and DataTables within the same user interface experience?

I'm currently facing a challenge with an application running in a sandbox environment where I am unable to create projects. Despite my efforts over the past few weeks, I can't seem to figure out how to get the DataTable to automatically select r ...