Angular 9属性长度-无法读取未定义的属性“长度”

时间:2020-05-11 15:49:39

标签: angular typescript

我在Angular 9和TypeScript中都有Web应用程序。 在html文件中,当字符串的长度小于10时,我想禁用按钮。 我的HTML代码:

<div class="p-2 form-group">
              <textarea type="text" class="form-control" id="inputCommentBody" placeholder="Text" [(ngModel)]="postCommentModel.body" rows="3"></textarea>
            </div>

<button class="btn btn-primary" (click)="addPostComment(post.id, null)" [disabled]="postCommentModel.body !== undefined || postCommentModel.body.length < 10">
              Add comment
            </button>

在TypeScript中,代码如下:

export class UserPageComponent implements OnInit {
  public postCommentModel: any = {};

我收到错误消息:

ERROR TypeError: Cannot read property 'length' of undefined
    at UserPageComponent_div_13_Template (user-page.component.html:113)
    at executeTemplate (core.js:12059)
    at refreshView (core.js:11906)
    at refreshDynamicEmbeddedViews (core.js:13283)
    at refreshView (core.js:11929)
    at refreshComponent (core.js:13358)
    at refreshChildComponents (core.js:11635)
    at refreshView (core.js:11958)
    at refreshDynamicEmbeddedViews (core.js:13283)
    at refreshView (core.js:11929)

2 个答案:

答案 0 :(得分:0)

您正在访问未定义的对象。解决方案是检查是否为null或未定义(以查看对象是否存在),然后进行迭代。

<button class="btn btn-primary" (click)="addPostComment(post.id, null)" [disabled]="postCommentModel.body === undefined || postCommentModel?.body?.length < 10">

答案 1 :(得分:0)

代码中的小错误

这里的目的是检查字段值的长度。

更改||对于&&运算符,它不会给出该错误。 这将确保 postCommentModel.body 具有该值,然后仅将其用于长度检查。

使用OR(||)运算符,因为 postCommentModel.body!== undefined为false ,它直接在页面加载时直接进入第二种条件。

<button class="btn btn-primary" (click)="addPostComment(post.id, null)" [disabled]="postCommentModel.body !== undefined && postCommentModel.body.length < 10">