Enhancing responsiveness in the auto-suggest feature

I am struggling to update the added value in the DOM after pushing a new element into the array of options. Despite my efforts, the update is not reflecting in the DOM.

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css'],
})
export class AutocompleteFilterExample implements OnInit {
  myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

 ngOnInit() {
  this.filteredOptions = this.myControl.valueChanges.pipe(
    startWith(''),
    map((value) => this._filter(value))
  );
 }

  private _filter(value: string): string[] {
  const filterValue = value.toLowerCase();

  return this.options.filter((option) =>
   option.toLowerCase().includes(filterValue)
  );
 }

 addOption() {
  this.options.push('Four');
 }
}

View the solution on StackBlitz

https://i.sstatic.net/OFHDg.png

Answer №1

Check out this stackblitz where your options automatically refresh upon clicking the "add" button.

The concept here involves utilizing the filteredOptions$ (following the convention of ending Observables with a $) which depend on two separate Observable streams:

  • Firstly, the input from the search field
  • Secondly, the options represented as an Observable that updates upon clicking the button

Answer №2

selections filters the user's input, so the user must enter something in order to view the newly added option in the dropdown menu.

One thing you forgot to do is update the filteredSelections with selections after the new value "Five" has been inserted.

  includeSelection() {
    this.selections.push('Five');
    this.filteredSelections = of(this.selections);
  }

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

Angular Universal - Transfer state does not populate correctly when the URL contains unsafe characters, leading to duplicate XHR calls

Working with Angular(12) and Angular Universal has presented me with a challenge regarding the transfer state between the server and client side. On the client side, I am using the TransferHttpCacheModule, while on the server side module, I have implemente ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

Is there a way to access VMWare localhost on a mobile device?

Currently, I am utilizing VM Ware for my development tasks and I am working on creating some responsive design code. Instead of using the web-developer tools' responsive layout emulator, I would like to view it in action on my mobile device. I am look ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Error: Parsing error - Unrecognized character "@" in Angular module

Currently I am delving into the realm of webpack and attempting to integrate it into my project. However, I seem to have hit a roadblock as I encounter the following error. Despite my efforts to troubleshoot and research, I cannot seem to find a loader spe ...

What is the best way to assign a default value in mat-select when using an ngFor loop?

Is there a different approach to setting a default value in mat-select within an *ngFor loop? I'm having trouble accessing the element in the array from the loop as desired. .ts file: persons: Person[] = .. //consist of Person with name and age .htm ...

Warning: The use of the ngModel input property and ngModelChange event with reactive form directives has been marked as obsolete

https://i.sstatic.net/EAWSR.png Encountered the following error: It seems that the usage of ngModel alongside formControlName on the same field is deprecated in Angular v6 and will be removed in Angular v7. After attempting to address this issue by remo ...

What is the best way to access a state variable that has a union data type?

Is there a way to access a field of a state variable with a union type in TypeScript? Here is an example of a zustand store I have defined: import { create } from 'zustand' type HeightUnit = 'cm' | 'ft\' in"&ap ...

Discovering Angular 2 Service Change Detection

Exploring the Angular 2 beta has led me to some challenges with understanding the change detection mechanism. I have put together a simple Plunker example that demonstrates an issue I am encountering. //our root app component import {Component, Injectab ...

Having trouble retrieving data from a local JSON file with Angular

I am attempting to retrieve data from a local JSON file in order to manipulate the data within the view. For example, if you choose UnitOne, the only available 'roles' you can select are 'role1', 'role2', 'role3', et ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

After deploying the application, the 'Access-Control-Allow-Origin' setting was not found

After deploying the same application to 2 servers (one for testing and one for production) on IIS, I encountered an issue. The application works perfectly on the first server, but not on the second one. While I am able to connect, retrieve data, and add ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

Encountering issues with vite build due to @types/react-router-dom package

I ran into an issue while developing my react app using Vite and TypeScript. Everything works fine when using Vite for development, but as soon as I switch to "tsc && vite build", I encounter numerous errors from @types/react-router-dom and @types/react-ro ...

Display a div above the Kendo for Angular Dialog

Looking at this StackBlitz example, there is a Kendo for Angular Dialog that contains a div with the CSS property position:absolute. The goal is to display this div on top of the dialog itself, rather than inside it, while ensuring that the dialog does n ...

Why am I encountering an issue while trying to access req.user.id?

Having set up passport authentication on my express, node project, I encountered an error when trying to access req.user. The error message displayed is Property 'id' does not exist on type 'User'.ts(2339). Below is the relevant code sn ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

"Customize the appearance of ng-bootstrap datepicker selection with a unique

Having trouble with the ng-bootstrap datepicker when selecting style for month and year. https://i.sstatic.net/grlK6.png The issue seems to be with the select style. select[_ngcontent-c21] { -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 0 .5re ...