Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 binding to maxlength of input or texarea

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).

like image 726
Mud Avatar asked Sep 29 '16 03:09

Mud


1 Answers

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

like image 101
Madhu Ranjan Avatar answered Nov 17 '22 19:11

Madhu Ranjan