javascript - 在 Angular 中使用文本输入的 maxlength 属性的问题
我正在尝试在输入字段上使用 maxlength 属性。以下是我的组件 HTML。
<div class="input-box-wrapper d-f" *ngIf="info[1] == false; else password">
<label class="lable" for="{{info[4]}}">{{info[0]}}</label>
<input class="p-10px c-w" type="{{info[3]}}" id="{{info[4]}}" placeholder="{{info[2]}}" maxlength="{{info[6]}}" (blur)="getValue($event)">
<div>{{info[6]}} that works fine</div>
</div>
<ng-template #password>
<div class="input-box-wrapper d-f p-r">
<label class="lable" for="{{info[4]}}">{{info[0]}}</label>
<input class="p-10px c-w" type="{{info[3]}}" #password1 id="{{info[4]}}" placeholder="{{info[2]}}" (blur)="getValue($event)">
<i class="fa fa-eye-slash p-a icon" aria-hidden="true" #icon1 (click)="chnageIcon()"></i>
<i class="fa fa-eye p-a icon show" aria-hidden="true" #icon2 (click)="chnageIcon()"></i>
</div>
</ng-template>我收到以下错误:
如果我设置了固定的 maxlength(例如 maxlength="10"),一切都正常。对我来说这似乎是一个错误,但如果我做错了什么,请告诉我
答案#1
插值和属性绑定只能设置属性,而不能设置属性值。maxlength 是一个属性,而不是原生属性,这就是你得到上述错误的原因。
查看 Angular 文档
使用属性绑定
[attr.maxlength]="variable_name"
<input class="p-10px c-w" type="{{info[3]}}" id="{{info[4]}}" placeholder="{{info[2]}}" [attr.maxlength]="info[6]" (blur)="getValue($event)">
答案#2
另一种写法是:
<input class="p-10px c-w" type="{{info[3]}}" id="{{info[4]}}" placeholder="{{info[2]}}" [maxLength]="info[6]" (blur)="getValue($event)">
通常情况下,你可以在属性周围使用方括号,并直接使用变量,而不是使用插值。
例如,你可以写成:
<input class="p-10px c-w" [type]=info[3] [id]=info[4] [placeholder]=info[2] [maxLength]=info[6] (blur)="getValue($event)">
