Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password.

I attempted to retrieve the values using JavaScript's getAttribute method, but unfortunately, it did not work as expected.

<password
                    [id]="passwordFieldId"
                    title="Password field"
                    placeholder="Enter a password"
                    [isValid]="isPasswordFieldValid"
                    [isDisabled]="isPasswordFieldDisabled"
                    [isRequired]="true"
                    type="password"
                    [minlength]= '5'
                    [maxlength] = '10'
                    [formControlName]="passwordFieldId"
                    [errorText]="errorText">
</password>



 public ngOnInit() {

        this.form = new FormGroup({
            [this.passwordFieldId]: new FormControl('', [Validators.required, Validators.minLength(/** unsure of input here */), Validators.maxLength(/** unsure of input here */)])
        });
    }

   public maxLength = this.form.get(this.passwordFieldId).get('maxlength');   

this returns undefined

Answer №1

To access the maximum length allowed for a password input field, you can use the component reference like so:

If you want to access it from the template, here's how:

<password
 #passwordInput
 [id]="passwordFieldId"
...

{{ passwordInput.maxlength | json }}

Alternatively, you can access it from the component class using ViewChild:

@ViewChild('passwordInput', { static: false }) password;
...

logValues() {
    console.log(this.password.maxlength);
}

For a live demonstration, check out this example.

Answer №2

Presented here is a demonstration form in Angular. Hopefully, this guide will be useful to you.

Typescript File 1. Imports

import{FormGroup, FormBuilder, Validators} from '@angular/forms';

2. Inside the Class form: FormGroup; 3. Inside Constructor

constructor() {

 this.form = this.formbuilder.group({
      passwordFieldId:['',Validators.compose([Validators.minLength(1), Validators.maxLength(6)])]
});
}

4. In HTML

<form [formGroup]="form">
<input type="password" formControlName="passwordFieldId" >
<button (click)="getPsw()"></button>
</form>

5. In Typescript

getPsw() {
console.log(this.form.passwordFieldId.value)
}

Answer №3

Why complicate things unnecessarily? Simply define two global variables within the component:

public minChars: number = 7;
public maxChars: number = 12;

Then utilize these variables in your template like so:

<input [minlength]="minChars" [maxlength]="maxChars">

And in the component:

this.formGroup = new FormGroup({
            [this.inputFieldId]: new FormControl('', [Validators.required, Validators.minLength(this.minChars), Validators.maxLength(this.maxChars)])
        });

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

Using an alias to call a function defined in a separate module in TypeScript

The following code snippet is from the v4.js file located inside the uuid folder within Angular's node_modules: var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { ...

Exploring Angular2: Incorporating External Plugins with AngularCLI (webpack)

Currently, I am in the process of developing an Angular2 application using AngularCLI with webpack version. A third-party plugin called ScrollMagic is being utilized which comes with optional plugins of its own. The main codebase for ScrollMagic has been i ...

Having difficulty implementing canDeactivate or canActivate in Angular

I am currently trying to integrate the canDeActivate and canActivate functions in my Angular 4 project. However, I seem to be encountering a no provider error. Can someone please guide me on what might be wrong with my implementation or suggest a cleaner a ...

Unable to correlate the response with the designated object

I'm currently facing an issue while attempting to utilize Angular4 HttpClient with an observable object that I've defined. My challenge lies in mapping the response to the designated object. The root of the problem appears to be related to my us ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Is it possible in RxJS to configure a ReplaySubject (or equivalent) that replays the latest messages with a distinctive identifier?

Is it possible to create a generic code that behaves like a ReplaySubject but emits each most recent message with a unique name upon subscribing? In the script below, the current output is... I want this to be logged once ... received the latest bbb 5 I c ...

The 'ngModel' property cannot be bound to the 'input' element as it is not recognized. Error code: ngtsc(-998002)

When attempting to add [(ngModel)]="email" to my Angular app, I encountered the error message "can't bind to 'ngModel' since it isn't a known property of 'input'". Despite already including import { FormsModule } fro ...

Understanding DefinitelyTyped: Deciphering the explanation behind 'export = _;'

Having trouble integrating angular-material with an ng-metadata project and encountering some issues. Utilizing DefinitelyTyped for angular material, the initial lines are as follows: declare module 'angular-material' { var _: string; expo ...

Steps to adding an item to a TypeScript array

My code involved creating an array called dataArray of type dataRows, which is an interface. dataArray: Array<dataRows>; In a function, I attempted to push a dataRows object into the array like this: this.dataArray.push(row) But for some ...

Guide to setting up Cosmos DB database connection using NestJS version 9.0.0

I'm encountering issues when attempting to include the Cosmos DB connection module in nestjs v9, as I'm facing dependency errors. Nest is unable to resolve the dependencies of the AzureCosmosDbCoreModule (COSMOS_DB_CONNECTION_NAME, ?). Please ens ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Angular will continue to stay on the current page unless the form is completed

Once a user logs in, they are directed to a form where they can enter their name and username. http://localhost:4200/form I need to ensure that the user fills out the form before being redirected to another page, even if they try to change the URL. In m ...

typescript Parameter type dependency based on value is not functioning

interface AddDataRequest{ data:any } interface AddDataResponse{ id:string } interface ITest{ addData(json:AddDataRequest):Promise<AddDataResponse> removeData(json:AddDataResponse):Promise<boolean> } function testInterface<A e ...

Choosing specific values from a dropdown menu in Angular to pass as parameters for an API call

I need to call an API with a parameter selected by the user from dropdown options. The issue I'm facing is that the API only returns results when all dropdowns are selected, not just one. I want to return results based on the single selection made by ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

The module 'AppModule' has unexpectedly declared a value of 'Component' that was not anticipated

Recently, I've been working on transitioning my application to the new angular2 webpack rc5 setup. I have successfully generated the app module using ng cli migration. However, I am facing an issue while trying to integrate a component from my own li ...

After updating to Angular 15, the web component fails to function properly on outdated versions of Chrome

Ever since upgrading Angular to version 15, my angular web component stopped functioning properly on Chrome 53. The issue seems to be related to the compilerOptions setting the target to ES2022. Upon checking the console, I am seeing the error message: Un ...

Oops! The program encountered an issue: Unable to retrieve information from an undefined property

I am completely new to using Angular and MongoDB. I am currently attempting to retrieve data from a MongoDB database and display it in an Angular Material Table. However, I encountered an error that reads: "ERROR TypeError: Cannot read property 'data ...

Encountering a CORS problem when an Angular application communicates with a .NET Core API integrated with the Sustainsys.Saml2 library and Azure Active Directory serving as the Identity

Our team is currently working on implementing SAML authentication in a .NET Core API to handle requests coming from an Angular application. We are utilizing the package Sustainsys.Saml2.AspNetCore2 (version 2.9.2) for .NET 6, and we have successfully set u ...

Angular and ag-Grid enable the addition of a convenient date picker to a date cell, simplifying the

Currently, I am working on an ag-grid in angular which has a cell containing a date. I want to enhance it by incorporating a date picker feature, however, the process seems quite intricate. My preferred choice would be to utilize mydatepicker, as it is alr ...