angular - textarea中的maxlength在Angular中不起作用

标签 angular typescript textarea maxlength

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

ERROR TypeError: Cannot read property 'maxlength' of null



我使用 maxlength 的表格的一部分:

<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: '',
        }

一旦我在文本区域中输入一些内容,错误就会开始出现。

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

最佳答案

它在提示尚不存在的东西的长度: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>

typescript
titleModel= 'I have more than 10 characters'

DEMO

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

如果你想让用户输入然后使用react,你可以放弃这种实现:
<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

关于angular - textarea中的maxlength在Angular中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46885065/

相关文章:

javascript - 如何设置这些按钮 'id' 值以附加到文本区域中?

java - 设置两个并排的 JTextArea Netbeans

jquery - 如何在 typescript 中使用 jQuery 控制轮播?

javascript - angular2/javascript 中的动态变量

Angular4 路由 : ResolveStart event never ends

css - 如何基于媒体查询动态传值

typescript - 如何组合多个 TypeScript 类装饰器?

angular - 将 #element 绑定(bind)到使用 *ngFor 创建的元素

javascript - typescript for 循环不执行

html - 文本区域布局问题