如何检查长度可以为空

huangapple go评论90阅读模式
英文:

How to check length which can be null

问题

我想检查一下我的文本区域长度。
这是我的代码:

<div class="row d-flex justify-content-center textarea-wrapper">
    <p class="mb-1">订单的附加信息:</p>
    <textarea class="additionalInformation justify-content-center" name="additionalInformation" value="{{additionalInformation}}" formControlName="additionalInformation" placeholder="文本..."
              [maxlength]="maxCharsOfArea"></textarea>

    <span *ngIf="signupForm.controls['additionalInformation'].value.length">
        {{signupForm.controls['additionalInformation'].value.length}} /{{maxCharsOfArea}}
    </span>
</div>

视图:

如何检查长度可以为空

在加载页面时,我收到错误消息无法读取 null 的属性(读取 'length')

添加任何文本后,一切正常运行。

如何检查长度可以为空

我该如何在初始化时处理这个问题?

英文:

I would like to check out my textarea length.
This is my code:


&lt;div class=&quot;row d-flex justify-content-center textarea-wrapper&quot;&gt;
    &lt;p class=&quot;mb-1&quot;&gt;Additional information to order:&lt;/p&gt;
      &lt;textarea class=&quot; additionalInformation justify-content-center&quot; name=&quot;additionalInformation&quot;
      value=&quot;{{additionalInformation}}&quot; formControlName=&quot;additionalInformation&quot; placeholder=&quot;text...&quot;
           [maxlength]=&quot;maxCharsOfArea&quot;&gt;&lt;/textarea&gt;

       &lt;span *ngIf=&quot;signupForm.controls[&#39;additionalInformation&#39;].value.length&quot;&gt;
     {{signupForm.controls[&#39;additionalInformation&#39;].value.length}} /{{maxCharsOfArea}}&lt;/span&gt;
&lt;/div&gt;

View:
<br>
如何检查长度可以为空

On Load my page I get error Cannot read properties of null (reading &#39;length&#39;)

After added any text, everything works perfect.
<br>
如何检查长度可以为空

What Can I do with this in intialization?

答案1

得分: 2

在这种情况下,您应该能够使用安全导航运算符 ?. 来避免您收到的错误。

{{signupForm.controls[&#39;additionalInformation&#39;].value?.length}} /{{maxCharsOfArea}}

如果您期望该值在初始化后保持为 null,您还可以添加一个空值合并运算符,将该值默认为 0。

{{signupForm.controls[&#39;additionalInformation&#39;].value?.length ?? 0}} /{{maxCharsOfArea}}

https://docs.angular.lat/guide/template-expression-operators#safe-navigation-operator

英文:

In this case you should be able to use the safe navigation operator ?. to avoid the error you are receiving.

{{signupForm.controls[&#39;additionalInformation&#39;].value?.length}} /{{maxCharsOfArea}}

https://docs.angular.lat/guide/template-expression-operators#safe-navigation-operator

If you expect that the value remains null after initialization, you could also add a nullish coalescing operator to default your value to 0

{{signupForm.controls[&#39;additionalInformation&#39;].value?.length ?? 0}} /{{maxCharsOfArea}}

huangapple
  • 本文由 发表于 2023年6月8日 16:42:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定