Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div.

This is what my template looks like:

<input type="text" id="jobTitle" 
(click)="autoCompleteClick()"
(keypress)="autoCompleteKeypress()" name="autocomplete" 
placeholder="Job Title" value="" >

The autoCompleteKeyPress function is supposed to be triggered by the keypress event and looks like this:

autoCompleteKeypress() {
    if (this.jobTitle == 'bar' || this.jobTitle == 'Bar'){
        alert('BOO!');
    } 
}

Currently just testing with an alert to make sure it's working.

Here is my full component code:

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

@Component({
    selector: 'sign-up',
    templateUrl: './sign-up.component.html',
    styleUrls: ['../variables.less', './sign-up.component.less']
})

export class SignUpComponent {
    imgPath = 'assets/images/';
    //acInput = document.getElementById('jobTitle');

    @Input() jobTitle : string;


    autoCompleteKeypress() {
        if (this.jobTitle == 'bar' || this.jobTitle == 'Bar'){
        alert('BOO!');
    } 
}

I am new to Angular2 and Typescript, so any suggestions are welcome. Thank you!

Answer №1

When you want to show or hide a div based on a specific input value, I recommend using the basic concept of Two-way binding along with the NgIf Directive. Here's how you can implement it:

<input type="text" [(ngModel)]="jobTitle" id="jobTitle"  name="autocomplete" placeholder="Job Title" value="" >
<div *ngIf="jobTitle === 'bar' || jobTitle === 'Bar'">
    Content to display
</div>

Answer №2

When trying to retrieve the input value within the context of this, it is important to note that simply assigning to an id will not suffice. The utilization of NgModel is necessary for this purpose. However, in this particular scenario, adding to a class variable is unnecessary.

To achieve the desired outcome, modify the HTML as follows:

<input type="text" id="jobTitle" 
(click)="autoCompleteClick()"
(keypress)="autoCompleteKeypress($event)" name="autocomplete" 
placeholder="Job Title" value="" >

Within the component, implement the following:

autoCompleteKeypress(event) {
     const jobTitle = event.target.value;
    if (jobTitle == 'bar' || jobTitle == 'Bar'){
        alert('BOO!');
    } 
}

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

Creating an Angular 2 project with DevExtreme in Visual Studio 2017/2015: A step-by-step guide

I would appreciate some guidance on setting up an Angular 2 project with DevExtreme control using Visual Studio 2017/2015. Specifically, I am interested in utilizing the control demonstrated at . Your assistance would be greatly appreciated. ...

Leverage JSON to produce an output with EventEmitter

The title captures the essence of my query perfectly. I am curious if there is a method to produce an output eventemitter through JSON in Angular, allowing me to receive specific events and perform additional tasks externally. ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Safeguarding user data across all components is facilitated by Angular 2

My Angular2 app uses OAuth2 with password grant type for authentication. I currently store the session token on sessionStorage, but I need to securely store additional data such as user roles. While I am aware that sessionStorage or localStorage can be ea ...

A component in Angular is able to inherit properties without the need to duplicate the constructor

I have been searching for a way to enhance the DRYness of my code by creating a solid Component parent. However, inheriting a Component from another Component requires duplicating the constructor(<services>){}, which goes against the DRY principle. T ...

How can I prevent Intellisense from automatically importing all global variables from Mocha (or any other testing library) into files that are not designated for testing purposes?

I am managing these files in the same directory. package.json: { "name": "example", "version": "1.0.0", "devDependencies": { "@types/mocha": "^7.0.1", "@types/node": "^13.7.1" } } tsconfig.json: {} index.ts: export const test = () =&g ...

What are the advantages of using interfaces in React?

Exploring Typescript's interface and its application in React has been an interesting journey for me. It seems that interfaces are used to define specific props that can be passed, acting as a form of protection against passing irrelevant props. My qu ...

Converting an HTML page to PDF with Angular using jsPdf and Html2Canvas

[1st img of pdf generated with position -182, 0, image 208,298 ][1]Converting an HTML page to PDF in Angular 8+ using jspdf and Html2canvas has been a challenge. Only half of the page is successfully converted into PDF due to a scaling issue. Printing th ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Utilize functional JS code within a TypeScript environment

Attempting to integrate this code into a TypeScript project, it is a modified version of the react-custom-scrollbars. I am struggling with TypeScript in regards to declaring types for style and props. In this particular case, I prefer to bypass type check ...

Necessary CSS selector input equivalent in Reactive Forms

Is there a similar CSS method like input:required {CSS} to style all the reactive form fields in Angular that are set as required using Validators.required in their formControl? Or is there another approach to achieve this with CSS? ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

The Angular functionality is functioning correctly on Mozilla browsers, but encountering issues on Chrome

I am looking to create a convenient page on my website for my team to easily access and copy the email template I have created to send to clients. The process would involve them visiting this page, clicking a button, and then pasting the email template dir ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

Leverage Webpack to bundle ES Modules with TypeScript module aliases

Hello there, I recently created an npm module using Typescript and ES-modules. Inside the /source folder, you can find my tsconfig.json file which includes a path alias. { "compilerOptions": { "moduleResolution": "Node ...

I am struggling to comprehend the concept of dependency injection. Is there anyone available to provide a clear explanation for me?

I am working on a NestJS application and trying to integrate a task scheduler. One of the tasks involves updating data in the database using a UserService as shown below: import { Injectable, Inject, UnprocessableEntityException, HttpStatus, } fro ...