12

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.

elzoy
  • 5,237
  • 11
  • 40
  • 65

3 Answers3

28

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thank you. It works like a charm but I notice that attr.maxLength works aswell. Is there some good practice to add attr. before attributes? – elzoy Jul 07 '16 at 15:18
  • 3
    `maxLength` is a native attribute and thus can directly be bound with `[maxLength]`. If you want to set a custom attribute like `data-id` for example, you can use the binding with `[attr.data-id]`. In the end it doesn't make a difference for those native attributes. – Maximilian Riegler Jul 07 '16 at 15:20
  • 1
    I see! Thank you for your help. Have a nice day. – elzoy Jul 07 '16 at 15:21
  • 2
    If it doesn't work without `[attr.` then add it ;-). Most properties are reflected to the DOM so if you set the property, the attribute gets created and vice versa. For others this doesn't work like for example `` doesn't work because the property name is `htmlFor` and the attribute name is for. If it is an `@Input()` of a custom component or directive and you don't need it on the DOM (for example to use it for CSS selectors) then it's better to not add `[attr.` because it means adding to the DOM which is much slower than property only. – Günter Zöchbauer Jul 07 '16 at 15:23
  • 1
    See also http://stackoverflow.com/questions/258469/what-is-the-difference-between-attribute-and-property – Günter Zöchbauer Jul 07 '16 at 15:23
17

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.

Lucio Mollinedo
  • 2,295
  • 1
  • 33
  • 28
9

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

<textarea [attr.maxLength]="textareaLength"></textarea>
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
  • 1
    Thank you very much. I regret that I can't accept two answers but u were late about 9 seconds. But of course, point for you :) – elzoy Jul 07 '16 at 15:20