9

I am new at Angular 2 and I have the following issue. I am trying to bind a component property to a native property of an input (maxlength) and I am not being able to do it.

The code is the following:

textbox.ts

@Component({
selector: 'icb-textbox',
inputs: [
    'placeholder',
    'mxlength',
    'enabled',
    'mandatory',
    'description',
    'type'],
templateUrl: 'Common/Components/Textbox/textbox.html',
styleUrls: ['Common/Components/Textbox/textbox.css']
})
export class Textbox {

    private placeholder: string;
    private mxlength: number;
    private enabled: boolean;
    private mandatory: boolean;
    private description: string;
    private type: string;
}

textbox.html

 <input type="text" maxlength="{{mxlength}}" [(ngModel)]="value" placeholder="{{placeholder}}" [disabled]="!enabled"/>

In the 'father' component:

<icb-textbox placeholder="Name" 
                 mxlength="4" 
                 [mandatory]="false" 
                 [enabled]="true" 
                 description="Put your name">

The properties 'placeholder' and 'disabled' are working ok, but I can make maxlength work. I have tried with [maxlength] and I get this error: Can't bind to 'maxlength' since it isn't a known native property.

Thank you.

Hernan Pintos
  • 175
  • 2
  • 9

3 Answers3

16

use

[attr.maxlength]= 'your value'

because by default angular look property binding. to tell angular to use explicitly we have used this syntax

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
13

Use instead

[attr.maxlength]="someValue"

or

attr.maxlength="{{someValue}}"

to explicitly bind to the attribute instead of the property.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

You can actually just bind directly to the maxLength property of the input by wrapping it with an attribute binding (square brackets).

So your HTML will look like this:

<input type="text" [maxLength]="mxLength">

And in your TypeScript file:

mxLength: string = 4;
lordchancellor
  • 3,847
  • 4
  • 26
  • 26