Setting maxLength attribute on a formcontrol dynamically in Angular

61 Views Asked by At

I want to set the maxLength for an input element in Angular dynamically. Currently I am doing something like this:

<input type="text" [formControlName]="name"
    [maxlength]="attribute.attributeName === AttributeName.FIRST_NAME ? 15 : attribute.attributeName === AttributeName.LAST_NAME ? 20 : 255">

but, this is not efficient in my opinion. I have a another scenario where I would need to check the condition for at least 15 different scenarios then set the maxLength.

I was wondering if there's any way to dynamically set it in the typescript file using @ViewChild?

2

There are 2 best solutions below

0
Rainy sidewalks On

try to grab following concept

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  maxLength: number = 20; //defult on load 1st

  updateMaxLengthDynm(newLength: number): void {
    this.maxLength = newLength; //change it as logic flow by call the function otherwise you can pass the function call 
     //or the logic directely to the oninit of course that req to implement onit in the class
  }
}

for the HTML

<input type="text" [maxLength]="maxLength">
<button (click)="updateMaxLengthDynm(25)">now press seting MaxLength to 25</button>
1
codewithharshad On
<input type="text" [formControlName]="name" [maxlength]="getMaxLength(attribute.attributeName)">




// Inside your component class
getMaxLength(attributeName: AttributeName): number {
  switch (attributeName) {
    case AttributeName.FIRST_NAME:
      return 15;
    case AttributeName.LAST_NAME:
      return 20;
    // Add more cases for other scenarios as needed
    default:
      return 255; // Default maxLength
  }
}