Angular gives priority to input when clicking an element

Please find the stackblitz link attached below.

https://stackblitz.com/edit/angular-dgx3pe

My goal is to achieve a functionality where clicking on the label element will focus on the input. This should trigger the input:focus class. I believe this can be done using JavaScript/jQuery, but I would prefer an Angular approach.

In essence, here are the two tasks I am trying to accomplish:

  • Focus on the input element when the label is clicked.
  • If the focus moves to another input and the previous one has content (i.e., not empty), the label should remain positioned at the top.

HTML

<input class="input" type="text">
<label class="label">Name</label>

<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}

Answer №1

  1. To reference your input text in the html, add #firstNameField and create a click event method for the label - (click)="focusOnFirstName()"
    <input #firstNameField class="input" type="text">
    <label class="label" (click)="focusOnFirstName()">First Name</label>

  1. Declare ViewChild in your component and implement a method to handle clicking on the label field.
      @ViewChild("firstNameField") firstNameField;

      focusOnFirstName(){
        this.firstNameField.nativeElement.focus();
      }

Answer №2

To achieve this using only markup, you must assign an id to the input field and use a for attribute in the label element

<input class="input-field" type="text" id="userInput">
<label class="label-name" for="userInput">Name</label>

It's important to note that labels can be linked to inputs based on their ids. By default, clicking on a label will focus on the associated input field. The id and for attributes need to match for this functionality to work properly.

For the second part of your query, if you want to apply existing CSS classes and toggle them based on a condition, you can create corresponding variables in your component. Use ngClass directive to include the .go-top class when the variable meets certain criteria

In your component file -

userName: string;

Then in your HTML code -

<input class="input-field" type="text" id="userInput" [(ngModel)]="userName">
<label class="label-name" for="userInput" [ngClass]="{'go-top': userName}">Name</label>

Answer №3

Looking at this task with a focus on creating an enhanced "Angular" solution for your specific conditional styling requirement. One effective approach would be to consolidate your input and label elements into a customized input component. Once you have established a new component using your initial elements as the base template, you can proceed with the following steps more efficiently.

The core strategy involves dynamically applying styles by leveraging Angular's [class] property binding or [NgStyle] directives.

  1. Initiate a ViewChild query on the template for the input element
    1. Implement an event listener on the input element within the template
    2. Upon detecting a keyup event, initiate a check on your <input> field value and update a class property indicating whether the field is empty
    3. Subsequent change detection will trigger updates to the element's class through [NgClass] or [class] bindings
//component.ts

import { Component, Input, ViewChild, ElementRef } from '@angular/core'

@Component({
  selector: 'app-input',
  styleUrls: ['./input.component.css'],
  templateUrl: './input.component.html'
})

export class InputComponent{
  @Input() labelName: string = "Your Label Here"
  @ViewChild("input") myInput:ElementRef<any> //ViewChild query

  empty: Boolean = true; // tracking input value truthiness

  isEmpty(){ // linked to keyup event on input element in template file

   if (this.myInput.nativeElement.value){
      this.empty = false;
    } else{
      this.empty = true;
    }
  }

  styles(){ // connected to [ngClass] directive binding on input element in template file
    return {
      'empty': this.empty ? true : false,
      'not-empty': this.empty ? false : true 
    }
  } 

}

//component.html with [ngClass] directive

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [ngClass]="styles()" (keyup) = "isEmpty()" #input>

//component.html utilizing [style] property binding
// here, empty refers to the .ts file property

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [class.empty]="empty" #input>

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

How do I go about adding <li> elements from component A to a favorites list in component B using Angular?

I'm currently working on a movie database project, and I'm trying to implement a feature where users can add movies from the "search-movie" component to a "favourites" component by clicking an "add to fav" button. I've been attempting to use ...

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

A comprehensive guide on integrating rappid.js and joint.js into an Angular 2 application

Exploring the possibility of integrating rappid and joint.js into a component of my Angular 2 application. Despite searching online, I haven't come across an example that fits my requirements. Is there a demo or guide available to show how this integ ...

The putImageData function claims that the given object is not an ImageData object, but upon inspection in the console, it clearly displays that it is

After using getImageData to store the pixels of an image in a two-dimensional array, I attempted to draw them with putImageData. However, I encountered an error indicating that the first parameter is not of type ImageData. Strangely, when I logged the vari ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

Steps for initiating a new dispatch once the previous one has concluded

Thank you for taking the time to read my query and offering your assistance. I apologize in advance for any language errors. I am currently working with redux and redux-thunk, and I am looking to trigger multiple dispatch actions in redux sequentially. Sp ...

What are the best strategies for mastering conditional promises in Angular?

I've been struggling with a problem in angularjs for several hours now. Here's the pseudo code I'm working with: doSomething(param){ var res; if(param = "ok"){ //perform some api calls with promises res = promise r ...

Tips for creating a unique custom rounded underline effect in an Angular Material Tab

Our design team has requested that we incorporate underlines that resemble the top half of a rectangle with rounded corners. We are currently using Angular Material, but I am facing difficulties in styling the existing tabs component (https://material.angu ...

Can multiple Observables be used to display FormArray data within a FormGroup effectively?

I've spent countless days attempting to asynchronously display dynamically loaded FormArray data without success. Essentially, I have a FormGroup that is created on click and shown in a modal window (no issues with displaying data loaded in the subscr ...

Utilize res.write to compress and stream content with gzip or deflate algorithms

const express = require('express'); const app = module.exports = express(); function getImages(callback) { callback(); } app .set('views', __dirname + '/views') .set('view engine', 'jade') .get('/ ...

Angular project is showing a unique error that says '$localize' is undefined according to Eslint

I successfully implemented localization in my Angular 15 project. However, I encountered an issue with linting for .ts files: error '$localize' is not defined no-undef Here's the configuration in my .eslintrc.json file: { "root": true, ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Retrieving the value of a JavaScript variable from an HTML document using Python

I am looking to extract the value of myJSONObject from an HTML document that includes javascript code with a JSON object. Here is an example snippet: <html> <head> </head> <body> <script type="text/javascript"> ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Sorting the keys of objects within an array

Currently, I am in the midst of an evaluation where I have the freedom to utilize any resources at my disposal. The task at hand involves using the .filter method to remove objects without a specific key. Here is the provided prompt... Create a function n ...

Modify the directory attribute based on a constantly changing variable

I need to adjust the dir attribute based on a variable that changes dynamically. <input [id]="'element'+i" [(ngModel)]="parent.firstName" class="form-control input-lg" ...

Retrieve the original jqXHR object from the success callback of the $.ajax function

My original task is as follows: Execute a jQuery.ajax() request. Upon success, perform additional checks on the data received from the server. If these checks fail, reject the promise for further handling. After researching extensively online, I came up ...