【问题标题】:Bind component attribute to native attribute of an input将组件属性绑定到输入的本机属性
【发布时间】:2016-02-15 18:50:39
【问题描述】:

我是 Angular 2 的新手,遇到以下问题。我正在尝试将组件属性绑定到输入的本机属性(最大长度),但我无法做到。

代码如下:

文本框.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;
}

文本框.html

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

在“父亲”组件中:

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

“占位符”和“禁用”属性工作正常,但我可以让 maxlength 工作。 我尝试使用 [maxlength] 并收到此错误:无法绑定到“maxlength”,因为它不是已知的本机属性。

谢谢。

【问题讨论】:

标签: angular


【解决方案1】:

使用

[attr.maxlength]= 'your value'

因为默认情况下角度外观属性绑定。为了明确地告诉 Angular 使用,我们使用了这种语法

【讨论】:

    【解决方案2】:

    改为使用

    [attr.maxlength]="someValue"
    

    attr.maxlength="{{someValue}}"
    

    显式绑定到属性而不是属性。

    【讨论】:

      【解决方案3】:

      您实际上可以直接绑定到输入的 maxLength 属性,方法是使用属性绑定(方括号)将其包装起来。

      所以您的 HTML 将如下所示:

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

      在你的 TypeScript 文件中:

      mxLength: string = 4;
      

      【讨论】:

        猜你喜欢
        • 2016-12-10
        • 2016-05-11
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多