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

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

How can I customize a Vue component slot in Storybook 8.0.6 using Vue 3.4 and Typescript to display various subcomponents within a story?

Incorporating a variety of sub-components into my Vue 3 component based on context is proving to be a challenge. Utilizing slots seems to be the solution in Vue 3, but I'm struggling to make it work within Storybook 8, which I'm using to showcase ...

Issue arises when attempting to use the useEffect hook in React with Typescript to reset states upon the component unmounting

I'm facing an issue with my useEffect cleanup when the component unmounts and setting states simultaneously. My code involves selecting a client by clicking on them and setting their ID to send in an API request: const setClient = () => { setC ...

Upgrade your AngularJS codebase with Angular 2+ services

Attempting to adapt an Angular 2+ service for use in an AngularJS project. app/users.service.ts import { Injectable } from '@angular/core'; @Injectable() export class UsersService { private users: any = [ { id: 1, name: 'john&a ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Error: Attempting to access the property 'cinemaName' of an undefined object

I am brand new to using angular2 and higher. My form definition with an input field of type text looks like this: <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label class="col-md-3 co ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

The directive for angular digits only may still permit certain characters to be entered

During my exploration of implementing a digits-only directive, I came across a solution similar to my own on the internet: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appOnlyDigits]' ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Comparing NativeScript and Flutter

Currently diving into the world of Native Script with Angular, I am fascinated by the code sharing capabilities that allow me to work on both web and mobile applications. However, a lingering question in my mind is why Google chose to develop Angular for ...

Leveraging Observables in an Angular 2 component to broadcast data to multiple components

Is it possible to utilize Observables in components and which other components can subscribe to them? BugListComponent - The component is injected in the boot.ts file where all services are loaded (where bootstrap is located) import {Subject, BehaviorSub ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

The 'roleName' property is not found within the 'never' data type

// ** React Component and Library Imports import { useEffect, useState } from 'react' import Box, { BoxProps } from '@mui/material/Box' import Button from '@mui/material/Button' import Drawer from '@mui/material/Drawer&ap ...

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

Struggling with making `http.get` function properly in Angular 2

Attempting to execute a basic GET request using Http in Angular 2, following guidance from this TUTORIAL and other current resources. Upon successfully injecting the http component, the following code was implemented constructor(@Inject(Http) /* remove ...

Encountering an error when using the Vue 3 TypeScript Composition API for style binding with an asynchronous

I utilized nexttick alongside an async method to update a DOM element. However, I am encountering issues with returning the correct style type. An error message pops up stating: error TS2322: Type 'Promise<{ maxHeight: string; }>' is not ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

`Next.js: Addressing synchronization issues between useMemo and useState`

const initializeProjects = useMemo(() => { const data: ProjectDraft[] = t('whiteLabel.projects', {returnObjects: true}) const modifiedData: ProjectWL[] = data.map((item, index) => { return { ... ...

What is the reason for deprecating the practice of utilizing data and errors in the subscribe/observable method in Angular?

What is the reason for this code being deprecated? And what is the proper format? fetchPeople() { this.peopleService.fetchPeopleList().subscribe( (data) => { console.log(data); }, (error) => { console.log(error); } ); } ...