gpt4 book ai didi

angular - 如何绑定(bind) 'maxlength' 属性?

转载 作者:太空狗 更新时间:2023-10-29 17:15:55 24 4
gpt4 key购买 nike

我可以渲染以下包含 <input> 的 Angular 2 组件用maxlength设置:

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

这很好用。但是,如果我尝试设置 maxlength通过绑定(bind),像这样:

@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<input> 的一个完全有效的属性元素。

这是一个 live example (打开控制台查看错误)。

最佳答案

摘自 Angular documentation ,

属性绑定(bind)

We become painfully aware of this fact when we try to write somethinglike 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, butinterpolation and property binding can set only properties, notattributes.

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

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

这是一篇关于 the difference between properties and attributes 的相关 Stack Overflow 帖子.

你可以试试下面,

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


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

这里是更新的并且有效 Plunker!!

关于angular - 如何绑定(bind) 'maxlength' 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com