Search code examples
angularangular2-template

How to bind 'maxlength' attribute?


I can render the following Angular 2 component containing an <input> with a maxlength set:

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

This works fine. However, if I try to set the maxlength via a 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 an <input> element.

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


Solution

  • excerpts from 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 a colspan property. It has the "colspan" attribute, but interpolation and property binding can set only properties, not attributes.

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

    Attribute binding syntax resembles property binding. Instead of an element property between brackets, we start with the prefix attr, followed by a dot (.) and the name of the attribute. We then set the attribute value, using an expression that resolves to a string.

    Here's a relevant Stack Overflow post about the difference between properties and attributes.

    You may 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!!