4

I have a form in angular and I want to use value of form "Validators.minLength" in html input tag.

I want Know is any way to use directly from form validator in html;

sample: [maxLength]="form.get('zipCode').validators('maxLength)"

My ts code is:

            zipCode: [ '', [
                Validators.required,
                Validators.maxLength(10),
                number,
            ],

and html is:

                        <input type="tel"
                               formControlName="zipCode"
                               [maxLength]="10"  // here I want insert dynamic number from ts file
                               placeholder="insert your zip code">

tanks for your helping.

2 Answers 2

2

TS

this.maxLength=10;
zipCode: [ '', [
                Validators.required,
                Validators.maxLength(this.maxLength),
                number,
            ],

HTML

<input type="tel" formControlName="zipCode" placeholder="insert your zip code">
Sign up to request clarification or add additional context in comments.

3 Comments

tanks for your answer, I want to know is a way to add maxlength value in input tag, sample: [maxLength]="form.get('zipCode').maxLength" ???
you can bind [maxLength] to a variable like this [maxLength] ="maxLength", but i didnt get the point, both are same right?
yes that's true but I have many fields same as this and it's not suitable way for me
1

TS:

public maxZipCodeLength: number = 10;

HTML:

<input type="tel" formControlName="zipCode" [maxlength]="maxZipCodeLength" />

This should be enough.

2 Comments

tanks for your answer, I want Know is any way to use directly from form validator in html; sample: [maxLength]="form.get('zipCode').validators('maxLength)"
That's bad way to do it. Keep in mind that according to official documentation if you use maxlength on html input, basically angular converts it to a form validator already. https://angular.io/api/forms/Validators#maxlength. That means if you use maxlength on input, you don't have to use validator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.