What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives:

<app-input ...></app-input>

My goal is to pass the blur event/function to the parent component specifically for the password field, so that I can retrieve its value and validate it based on a RegEx pattern.

I have spent quite some time searching (including on SO) and trying various options, but none of them provided the desired clean behavior.

Continuously receiving the error message:

el => undefined

The challenge seems to be how to pass the exact element Ref to form.component.html so that the function can be executed on the specific input field which happens to be the password field in this case.

Using Angular: 5.2.10

input.component.html:

<mat-form-field>
    <mat-label>
        <mat-icon matPrefix>lock</mat-icon>
        <span>{{ inputLabel }}</span>
    </mat-label>
    <input matInput type="{{inputType}}" name="{{inputName}}" [(ngModel)]="model" (ngModelChange)="modelChange.next($event)" required="{{required}}" pattern="{{regEx}}" (blur)="onFieldBlurClient('name.value')">
    <mat-error align="end">
        {{ inputError }}
    </mat-error>
</mat-form-field>

input.component.ts:

export class InputComponent implements OnInit {

    public parentFormGroup: FormGroup;

    @Output() onFieldBlur: EventEmitter<any> = new EventEmitter<any>();
    @Input('label') inputLabel: string;
    @Input('name') inputName: string;
    @Input('validationError') inputError: string;
    @Input('type') inputType: string;
    @Input('pattern') regEx: string;
    @Input() required = true;

    @Input() model: any;
    @Output() modelChange = new EventEmitter();

    constructor() {
    }

    ngOnInit() {
    }

    onFieldBlurClient(el) {
        this.onFieldBlur.emit(true);
    }

}

form.component.html:

<app-input [label]="'Password'" 
           [type]="'password'" [name]="'password'" 
           [validationError]="'Pass is not valid'" 
           [required]="true" 
           [parentFormGroup]="form" 
           [pattern]="(password_rexExp)" (onFieldBlur)="onBlur()"> . 
</app-input>

form.component.ts:

export class FormComponent implements OnInit {
    ....
    public password_regExp
    public toggleRegExCheck = false;
    ...

    constructor() {
        this.password_regExp = '......';
    }

    ngOnInit() {
    }

    public onBlur(el) {
        console.log(`el => ${el}`);
        if (!password_regExp.test(el)) {
           this.toggleRegExCheck = true; 
        } else {
           this.toggleRegExCheck = false;
        }
    }
}

Answer №1

transfer the Event

(onFieldBlur)="onBlur($event)"> . 

Answer №2

In order to retrieve the current item's value, you must include the $event parameter in your template function call.

<app-input [label]="'Password'" 
       [type]="'password'" [name]="'password'" 
       [validationError]="'Pass is not valid'" 
       [required]="true" 
       [parentFormGroup]="form" 
       [pattern]="(password_rexExp)" (onFieldBlur)="onBlur($event)"> . 

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

JavaScript for Loading and Moving Ads in IE8

On my website at , I have placed my AdSense ads at the top of the page. However, I encountered an issue with Internet Explorer 8 where the Javascript code I used to move the ads to a different position on the page doesn't seem to work: <!-- POSI ...

Angular to always show loading spinner on page load

Utilizing my Angular project with the Ant Design NG Zorro loading spin. I encountered an issue where the loading spin is continuously active on my Angular page. Does anyone know the correct way to implement this loading spinner? Thanks View the example o ...

Using axios to pass parameters in a post request

In my webpack project, I am currently using vue-resource for ajax calls. Everything works perfectly with "get" calls, but when I try a post request, my PHP file does not receive any parameters. Even when I use var_dump($_POST), it just gives me an empty ar ...

Jaydata is a powerful open source library for interacting with databases

I rely on jaysvcutil for compiling OData $metadata and generating JayDataContext.js, which is truly impressive. However, I prefer to work with Typescript without using import/export syntax or other third-party tools like requirejs or systemjs. Even thoug ...

When using sequential jQuery 'pages', an error referencing the third frame occurs

I am new to using javascript/jquery and have been experimenting with the w3schools tutorials and jquery documentation. I created a page where user input is accepted and javascript prints output based on that input. I tried modifying it to work sequentially ...

Utilizing AJAX to dynamically populate a dropdown menu with data from a SQL

Having recently delved into the world of ajax, I have a basic understanding of how it works. I've implemented a registration form that dynamically updates the fields for "country, city, and area" using ajax to fetch data from a database. The PHP code ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

The issue persists with react-hook-form and Material UI RadioGroup as the selected value remains null

Having trouble with RadioGroup from Material UI when using react-hook-form Controller. I keep getting a null selected value, even though my code seems right. Can you help me figure out what's missing? import * as React from "react"; import { ...

Ways to implement CSS with javascript

I'm using PHP to retrieve data from my database and then leveraging Javascript to enable users to add it. However, I am facing challenges in making a div change its background color and apply borders. <div class="displayedItems"></div> &l ...

The HTML table seems to be inexplicably replicating defaultValue values

I'm encountering an issue where, when I use JavaScript to add a new table data cell (td), it ends up copying the defaultValue and innerText of the previous td in the new cell. This is confusing to me because I am simply adding a new HTML element that ...

Is there a method in Angular to refresh or recompile a specific section or entire page that utilizes one-time bindings?

With numerous lists on our page containing potentially hundreds of items, we prioritize performance by implementing one-time bindings to update only when necessary and minimize the number of watchers. If we decide to utilize one-time bindings, is there a ...

JavaScript - Dynamic rotation algorithm

I recently developed a piece of code to manage object rotation in a THREE.js environment. Although the issue is not specific to 3D. My goal is to have my object (referred to as 'this') rotate by 0.25 radians each time a function is called, until ...

404 error occurs when routing in Express.js is unable to find the

Seeking Assistance I am encountering an issue with my express.post() routing as it returns a 404 state. Current Implementation The code in my server.js file seems fine, but I am facing this routing problem. // Required modules and database connection v ...

Finding the precise Time zone with date-fns: A comprehensive guide

I've implemented a date pipe using the date-fns library for formatting dates. Here is the code: date.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { format } from 'date-fns'; @Pipe({ name: 'formatDate ...

Extracting date information from an HTML table for use in Highcharts

Trying to utilize HighCharts' HTML-table-to-chart script for generating a line graph from a table. Desiring to set a datetime x-axis, so the following steps have been taken: Utilizing Date.parse(this.innerHTML) to convert row headers into date stri ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

Having trouble uploading an image to AWS using Angular and NodeJS?

I am currently working on a Node/Express application and I need to gather file information for uploading from an Angular/Ionic front end. To achieve this, I have created a separate Service in Angular that successfully retrieves the Image name. However, my ...

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Safari failing to load JavaScript on live website

While JavaScript functions correctly both locally and in production on Chrome, I am facing issues when trying to run it on Safari. Despite having JavaScript enabled on Safari and it working fine locally, it fails to work on the production environment. This ...