Angular 2 binding to maximum input or texaria length

I can display the following Angular 2 component containing the input with the maxlength set:

@Component({ selector: 'app', template: '<input maxlength="10">', }) export class App { } 

It works great. However, if I try to set maxlength through the binding, like this:

 @Component({ selector: 'app', template: '<input [maxlength]="maxLength">', }) export class App { maxLength = 10; } 

Or like this:

  template: '<input maxlength="{{maxLength}}">', 

I get the following error:

 "Template parse errors: Can't bind to 'maxlength' since it isn't a known property of 'input'." 

Why? maxlength is a perfectly valid property of the input control.

Here's a live example (open the console to see the error).

+6
source share
1 answer

excerpts from the Angular documentation ,

Attribute Binding

We become painfully aware of this fact when we try to write something like this:

 <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> We get this 

Error:

 Template parse errors: Can't bind to 'colspan' since it isn't a known native property 

As the message says, the element does not have the colspan property. It has the colspan attribute, but interpolation and property binding can only set properties, not attributes.

We need attribute bindings to create and bind to such attributes.

The attribute binding syntax resembles property binding. Instead of an element between brackets, we start with the attr prefix, followed by a period (.) And an attribute name. Then we set the attribute value using an expression that resolves the string.

Here is the corresponding record of the difference between properties and attributes .

You can try below

 @Component({ selector: 'app', template: '<input [attr.maxlength]="maxLength" >', }) export class App { maxLength = '10'; } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {} 

Here is the updated and it works Plunker !!

Hope this helps!

+21
source

All Articles