Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind component attribute to native attribute of an input

Tags:

angular

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.

like image 527
Hernan Pintos Avatar asked Feb 15 '16 18:02

Hernan Pintos


People also ask

What is used to bind a component property?

To bind the src property of an <img> element to a component's property, place src in square brackets followed by an equal sign and then the property.

What is difference between property binding and attribute binding?

In property binding, we only specify the element between brackets. But in the case of attribute binding, it starts with the prefix attar, followed by a dot (.), and the name of the attribute. You then bind the attribute value using an expression that resolves to a string.

Why we use attribute binding in Angular?

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.

What is 2 way data binding in Angular?

The two-way data binding in Angular is used to display information to the end user and allows the end user to make changes to the underlying data using the UI. This makes a two-way connection between the view (the template) and the component class. This is similar to the two-way binding in WPF.


1 Answers

Use instead

[attr.maxlength]="someValue"

or

attr.maxlength="{{someValue}}"

to explicitly bind to the attribute instead of the property.

like image 164
Günter Zöchbauer Avatar answered Sep 22 '22 00:09

Günter Zöchbauer