尽管错误无法读取 null 的属性长度,但代码有效 [英] Despite error cannot read property length of null, the code works

查看:22
本文介绍了尽管错误无法读取 null 的属性长度,但代码有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说看起来不错.

This looks pretty good to me.

<mat-form-field class="example-medium-width">
  <textarea matInput name="description" [(ngModel)]="description" placeholder="Description" maxlength="50"  #field_description="ngModel">
  </textarea>
  <mat-hint align="end">
     {{field_description.value.length}} / 50 Chars please.
   </mat-hint>
</mat-form-field>

但是由于某种原因,浏览器不高兴!

But for some reason, browser is not happy!

错误类型错误:无法读取 null 的属性长度"在 Object.eval [as updateRenderer] (CreateLearningPlanComponent.html:75)

ERROR TypeError: Cannot read property 'length' of null at Object.eval [as updateRenderer] (CreateLearningPlanComponent.html:75)

但是,当我在 text-area 元素中键入字符时,我可以看到正确报告了值(即 text-area 中的当前字符数)!所以我看到 1/50 ... 2/50.这告诉我并最终在第 50 个字符处停止用户输入.所以 field_description.value.length 似乎没问题.

However, as I type characters into the text-area element, I can see the value ( the current number of chars in the text-area that is) is correctly being reported! So I see 1/50 ... 2/50. and this tell me that and stopping the user input eventually at the 50th char. So the field_description.value.length seems to be OK.

然后长度未定义!

但是您认为为什么我会在 console.log 上收到此错误?

But why do I get this error on the console.log you think?

推荐答案

你应该使用安全导航操作符,

You should use safe navigation operator,

<mat-hint align="end">
     {{field_description?.value?.length}} / 50 Chars please.
</mat-hint>

这篇关于尽管错误无法读取 null 的属性长度,但代码有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆