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

Applying multiple classes and conditions with Angular's NgClass directive

I am currently working on implementing a feature where the class name of a component within a div can be changed based on a button click. There are approximately five CSS classes that I would like to toggle on and off using ng-class. My main question is ...

The NestJS Backend is always being asked by Grafana to access the /api/live/ws endpoint

After successfully setting up Grafana and Grafana Loki with my NestJS Backend, everything seemed to be working fine. However, I started getting a 404 error from my NestJS because Grafana was requesting the /api/live/ws route. Is there a way to disable thi ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

A comprehensive guide on organizing JavaScript files within an Angular project

In the process of building my MEAN app, I have structured my folders in the following way: I have included a js file in /angular/src/assets/js for jQuery functionalities. To achieve this, I utilized npm to install jQuery. Now, I am faced with the task o ...

errors.ts:30 ERROR Error: Unhandled promise rejection: Error: No routes found for specified URL Segment: 'products,%20productId'

I'm in the process of learning Angular by following a tutorial on a website. You can find it here: https://angular.io/start/routing Everything is going smoothly so far, except for the section on routing. If I add 'products/1' to the end of ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...

An issue occurred while attempting to retrieve Firebase data using an HTTP GET request

When trying to retrieve my data from firestore using an HTTP get request, I encountered an error. It might be helpful if my data in firestore was stored in JSON format. I'm not sure if this is feasible. <!DOCTYPE html> <html lang="en"> ...

Encountering an Error: Unforeseen Token < Causing Webpack Configuration Problem in Typescript

Seeking assistance to resolve an issue that has arisen while working on a project with Typescript, React, and Webpack. I referred to the guide available at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html After configuring everything, ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Tips for securely accessing a parameterized property of an object in Typescript

I need to create a function that takes an object as an argument and accesses a specific property of this object based on another parameter. Here is the code snippet: // javascript code function setProperty(subject, property, value) { subject[property] ...

Issue: Module compilation unsuccessful (from ./node_modules/css-loader/dist/cjs.js) during upgrade from Angular 11 to Angular 16

Summary: Can anyone help with a strange error I encountered while updating my Angular application? Situation: After finally updating my Angular 11 app to Angular 16, I faced several fixable errors along the way. However, one particular error is now hind ...

Decoding the mysteries of a ZoneAwareError: A guide to unraveling the enigma

Within my Angular 2 application, I utilize a resolve guard that performs an XHR request and throws a custom error if the request fails: return this.service.getProduct (id) .catch (err => Observable.throw(new MyError(err.message, route, 500, err))); ...

Typescript: Select just one option from the union

There is a specific Query type that contains the getBankAccounts property: export type Query = { getBankAccounts: GetBankAccountsResponseOrUserInputRequest, }; This property can return either a GetAccountsResponse or a UserInputRequest: export type Ge ...

What is the best way to modify the disabled attribute?

After disabling a button using a boolean variable, updating the variable does not remove the disabled attribute. How can I update my code to enable the button when the variable changes? Here is my current code snippet: var isDisabled = true; return ( ...

The CORS policy is blocking Angular Socket.io Node.js because the requested resource does not have the 'Access-Control-Allow-Origin' header present

When trying to access the socket endpoint from my frontend, I encounter this error message: chat:1 Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NOAlAsz' from origin 'http://localhost:4200& ...

What is the process for retrieving the API configuration for my admin website to incorporate into the Signin Page?

My admin website has a configuration set up that dynamically updates changes made, including the API. However, I want to avoid hardcoding the base URL for flexibility. How can I achieve this? Please see my admin page with the config settings: https://i.st ...

Applying styles to every tr element in Angular 2 components

I'm trying to use background-color with [ngClass] on a table row. The styles are being applied, but they're affecting all rows' backgrounds. I want the background color to only change for the specific row that is clicked. Here is my code: ...

Creating a custom extended version of Angular2 Http does not automatically provide injection of services

I'm struggling to understand this issue. I've created a custom class that extends Angular's Http class. import { Injectable } from '@angular/core'; { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, ...

Can Angular Universal SSR be activated specifically for Googlebot User Agents?

I am aiming to activate Angular Universal SSR only when the User Agent is identified as Googlebot. However, I am uncertain about how to instruct Angular Universal SSR to deliver server side rendered HTML exclusively if the User Agent is Googlebot. server ...