Only the initial letter of the angular input is returned by the event

Question: Why is the event only capturing the first letter of the input form?

Background: In an input form, users can type a string but the method I created to handle the event is only recognizing the first letter entered. For example, if someone types "hello," the event handler fires in this order 'h' 'e' 'l' 'l' 'o'

I have attempted to capture the value and push it to an array, but I have not been successful in achieving the desired result.

Intended outcome: My goal is to dynamically store the letters in an array within the method so that if a user deletes a character, it would be reflected in the array.

The template

<mat-form-field appearance="outline" class="name-search">
    <mat-label>Search Stands</mat-label>
    <button mat-icon-button matSuffix>
        <mat-icon>search</mat-icon>
    </button>
    <input matInput type="text" (input)="onSearchTextChanged($event)" />
</mat-form-field>

The logic


export interface Filter {
    query: string
    groupBy: GroupBy
}

interface GroupBy {
    field: string
    value: string
}

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

  
    @Output() searchTextChanged: EventEmitter<Filter> = new EventEmitter()


    filter = {
        query: '',
        groupBy: { field: 'status', value: this.statusGroupBy },
    }

    constructor() {}

    ngOnInit(): void {}


    onSearchTextChanged(event) {
        const { data } = event

        const filter: Filter = {
            ...this.filter,
            query: data,
        }
        this.searchTextChanged.emit(filter)
    }
}

Answer №1

If your question is about how to detect which key a user has pressed, you can utilize the standard keyup event handler.

Here's an example component:

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

@Component({
  selector: 'input-with-keyup-event',
  template: `<mat-form-field appearance="fill">
               <mat-label>Input with KeyUp event handling</mat-label>
               <input matInput type="text" [(ngModel)]="value" (keyup)="onKeyUp($event)" />
             </mat-form-field>`
})
export class InputWithKeyUpEvent {
  value = '';
  onKeyUp(event: KeyboardEvent): void {
    //You can add your custom logic here. For now, it just logs the pressed key:
    console.log(event.key);
  }
}

Answer №2

When observing the value stored in data, it reflects the specific typed character at that moment.

If you aim to retrieve the entire value of the <input> element, use

(event.target as HTMLInputElement).value
.

onSearchTextChanged(event) {
  const { data } = event as InputEvent;

  const filter: Filter = {
    ...this.filter,
    query: (event.target as HTMLInputElement).value,
  };
  this.searchTextChanged.emit(filter);
}

In the parent component, to obtain the string in the form of a Character array:

get charArray(): string[] {
  return Array.from(this.result?.query || []);
}

Check out the Demo on StackBlitz

Answer №3

I decided to connect the input to a FormControl. Click here for more information on form Control.

Template

<mat-form-field appearance="outline" class="name-search">
    <mat-label>Search Stands</mat-label>
    <button mat-icon-button matSuffix>
        <mat-icon>search</mat-icon>
    </button>
    <input matInput [formControl]="searchControl" />
</mat-form-field>

Logic

export class StandsSearchbarComponent implements OnInit {
    @Output() filterUpdate: EventEmitter<Filter> = new EventEmitter()


    searchControl = new FormControl()
    querySubscription = this.searchControl.valueChanges
        .pipe(
            distinctUntilChanged(),
            startWith('')
        )
        .subscribe((query) => this.onSearchTextChanged(query))

    filter = {
        query: '',
        groupBy: { field: 'status', value: this.statusGroupBy },
    }

    constructor() {}

    ngOnInit(): void {}


    onSearchTextChanged(query: string) {
        const filter: Filter = {
            ...this.filter,
            query: query,
        }
        this.filterUpdate.emit(filter)
    }
}

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

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

Angular application unable to invoke the Web API GET method

Just starting out with Angular. I've got a WebAPI controller set up with a get method that returns data. Everything runs smoothly when I access it from the browser directly. But for some reason, when I try to call the same method from my Angular ap ...

Employing Angular CLI for reverse proxying to an API Gateway/lambda service

I'm attempting to reverse proxy Angular by utilizing the proxy.conf.json file to connect to a lambda function behind API gateway. { "/api/profile/*": { "target": "http://asdasdfsdf.execute-api.ap-southeast-2.amazonaws.com", "secur ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

Having trouble setting up Typescript in VisualStudio 2015 due to the error message "exports is not defined"? Need guidance on the correct setup?

I am new to TypeScript and I am currently learning about exports and imports in TypeScript However, as I started working on it, I encountered an error with exports Object.defineProperty(exports, "__esModule", { value: true }); The error message I receiv ...

What is the process for importing from a `.d.ts` file?

This code snippet is functioning properly in a project built with angular2 RC4 import * as mapTypes from '../../../../node_modules/angular2-google-maps/core/services/google-maps-types.d.ts'; What could be causing this issue? Now, when attempti ...

How can a class be added to only the initial row in Angular2?

I'm looking to dynamically add a CSS class under certain conditions. Within the code snippet below, I am trying to assign the RowHeaderCSS class to the first row of the table. However, it doesn't seem to be working as expected. Can anyone provid ...

Altering the inner HTML content of a div using the ID within an Angular component function

Attempting to change the inner HTML content of a div using its id with another div in an Angular component method. Successfully calling the populateEndpointHomeContent() method and retrieving the content, but encountering issues with subsequent content. Th ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

In Internet Explorer, the loading time of an Angular 2 webpack application is being delayed by the presence of excessive ".js.map" files

https://i.stack.imgur.com/sY0tJ.pngEvery time I attempt to launch my Angular 2 webpack application on IE11, it noticeably takes longer to load compared to using Chrome. Upon inspecting the Network tab, I noticed that IE is attempting to fetch multiple fi ...

What is the best way to define a model class within my Angular 2 component using TypeScript?

As I delve into Angular 2 and TypeScript, I am keen on adopting best practices. I have decided to move away from a simple JavaScript model ({ }) in favor of creating a TypeScript class. However, it seems that Angular 2 is not very fond of my approach. T ...

Uploading images to an S3 bucket using Angular4 and saving the response.Location in a global variable for easy access in other functions or methods

Hello, I am currently working on uploading an image to an Amazon S3 server using Angular 4. My goal is to retrieve the response.Location, which is returned from S3 as a URL, and save it to a global variable for easy access. However, I am facing some challe ...

The onSubmit function in Formik fails to execute if there are no input values present

I am currently working on building a form using Next.js, TypeScript, and the Formik + Yup libraries. I've encountered two scenarios: one where an input field is visible and Formik captures the value, and another where the input is not visible and the ...

I believe my routing may be incorrect. Alternatively, the issue might lie elsewhere

I am facing an issue with Angular routing, where I want the navigation bar to persist while changing the background. However, the navigation bar overlaps on top of the background when I try to achieve this. [! [Check out my routing file] (https://i.stack. ...

Tips for customizing the color of a leaflet-routing-machine marker

I'm currently utilizing the leaflt-routing-machine plugin, and I'm looking to alter the color of markers from blue to red. Any ideas or suggestions on how to achieve this?! ...

Determining the data type of a generic variable within an Angular component

I'm currently in the process of developing a versatile component that can handle data of only two specific types: interface X{ name: string, path: string, type: string, } interface Y{ name: string, path: string, } Both types X a ...

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

Convert all key types into arrays of that key type using a TypeScript utility type

My interface (type) is currently defined as: interface User { name: string, id: string, age: number, town: string } I have a function now that will search for Users based on specific fields. I prefer not to manually declare an additi ...

Task ':processDebugGoogleServices' could not be added because there is already a task with the same name

Trying to test out the firebase FCM plugin, but encountering numerous errors along the way. After resolving most of them, I attempted to perform the following command: ionic cordova build android, only to be faced with the following error: Here's wha ...

Storing Data Efficiently within a Service

I'm completely new to the world of rxjs and asynchronous programming. When a component inquires about data from my service, I want to make sure that I fetch the data from my API only if it's not already available. Here's an example of how I ...