2016-09-29 65 views
6

我可以呈現含有具有最大長度設定輸入以下角2成分的最大長度:角2結合到輸入或texarea

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

這工作得很好。但是,如果我嘗試通過綁定設置最大長度,就像這樣:

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

或者這樣:

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

我得到以下錯誤:

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

爲什麼? maxlength是輸入控件的完全有效屬性。

這是一個live example(打開控制檯查看錯誤)。從Angular documentation

回答

19

,摘編,

屬性綁定

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.

這裏有一個相關的堆棧溢出後約the difference between properties and attributes

您可以嘗試以下,

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


@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

這裏是更新和它的作品Plunker!!

希望這有助於!

+0

非常感謝。這是什麼意思,它是怎麼發生的,是否有關於它的文檔等?我只需要知道如何向我的同事解釋這一點。 – Mud

+0

你可以在[angular文檔](https://angular.io/docs/ts/latest/guide/template-syntax.html#!#other-bindings)上閱讀有關屬性綁定,乾杯! –