textarea 中的最大长度在 Angular 中不起作用

maxlength in textarea not working in Angular

我在我的表单中使用了 maxlength,但它抛出了错误

ERROR TypeError: Cannot read property 'maxlength' of null

我使用最大长度的部分表格:

<div>
   <textarea AutoExpandTextArea [inputData]='model.title' maxlength="100" class="videoTitle" name="videoTitle" id="videoTitle" #videoTitle="ngModel"  placeholder="Title" [(ngModel)]="model.title" required>{{model.title}}</textarea>
  <span class="text-danger" *ngIf="submitted && loginform.form.invalid && videoTitle.errors.required">Title is mandatory</span>
  <span class="text-danger" *ngIf="videoTitle.dirty && videoTitle?.errors.maxlength">Maximum 100 characters are allowed</span>
   <textarea AutoExpandTextArea [inputData]='model.description' maxlength="120" class="videoDescription" id="videoDescription" name="videoDescription" #videoDescription="ngModel" placeholder="Description" [(ngModel)]="model.description">{{model.description}}</textarea>
   <span class="text-danger" *ngIf="videoDescription.dirty && videoDescription?.errors.maxlength">Maximum 120 characters are allowed</span>

</div>

页面加载时模型对象如下所示

this.model = {
            description: '',
            title: '',
        }

只要我在文本区域中输入内容,错误就开始出现。

我有一个指令也绑定到文本区域。不确定这是否导致了问题。

它抱怨尚不存在的内容的长度:videoDescription?.errors。

您可以在errors videoDescription.errors?.maxLength 后添加安全导航运算符。就像这个例子:

HTML

 <textarea required maxlength="10" 
    name="titleId" [ngModel]="titleModel" 
    (ngModelChange)="titleModel = $event + ''" #titleId="ngModel" ></textarea> 

 <span style="color:red" *ngIf="titleId.errors?.required">
          required
 </span>
 <span style="color:red" *ngIf="titleId.errors?.maxlength">
          10 max
 </span>

打字稿

titleModel= 'I have more than 10 characters'

DEMO

这有效,但 maxLength 会阻止在限制后输入更多字符,因此只有在您以编程方式设置时才会显示验证消息。


如果你想让用户输入然后反应,你可以放弃这种实现:

<textarea class="form-control" id="title" maxlength="10" 
name="title" [(ngModel)]="titleModel"></textarea> 
<span style="color:red" *ngIf="titleModel?.length > 10">
      10 max
</span>

DEMO