Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 maxLength for textarea as variable

To set max letters number for textarea, we do achieve that by writing: <textarea maxLength="50"></textarea>

but, could I do something like below? Is there some way?

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

@Component({
  moduleId: module.id,
  selector: 'app-create-offer-page',
  template: `
    <textarea maxLength="textareaLength"></textarea>
  `
})
export class CreateOfferPageComponent {
  textareaLength: number = 50;
}

I'm asking because that does not work.

like image 383
elzoy Avatar asked Jul 07 '16 15:07

elzoy


3 Answers

You would need [] for Angular to interpret it as binding

 [maxLength]="textareaLength"

This should work for native validation. Angular2 validators don't currently support dynamic values.

like image 172
Günter Zöchbauer Avatar answered Oct 13 '22 20:10

Günter Zöchbauer


Expanding a little bit on the answer provided by @rinukkusu, you could even make the attribute optional by adding a ternary operator, like so:

<textarea [attr.maxLength]="textareaLength > 0 ? textareaLength : null"></textarea>

The null value removes the attribute completely from the element, which was something I needed.

like image 34
Lucio Mollinedo Avatar answered Oct 13 '22 21:10

Lucio Mollinedo


Sure and it's pretty easy - just use attribute binding like so:

<textarea [attr.maxLength]="textareaLength"></textarea>
like image 43
rinukkusu Avatar answered Oct 13 '22 20:10

rinukkusu