英文:
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:
<div class="row d-flex justify-content-center textarea-wrapper">
<p class="mb-1">Additional information to order:</p>
<textarea class=" additionalInformation justify-content-center" name="additionalInformation"
value="{{additionalInformation}}" formControlName="additionalInformation" placeholder="text..."
[maxlength]="maxCharsOfArea"></textarea>
<span *ngIf="signupForm.controls['additionalInformation'].value.length">
{{signupForm.controls['additionalInformation'].value.length}} /{{maxCharsOfArea}}</span>
</div>
On Load my page I get error Cannot read properties of null (reading 'length')
After added any text, everything works perfect.
<br>
What Can I do with this in intialization?
答案1
得分: 2
在这种情况下,您应该能够使用安全导航运算符 ?.
来避免您收到的错误。
{{signupForm.controls['additionalInformation'].value?.length}} /{{maxCharsOfArea}}
如果您期望该值在初始化后保持为 null,您还可以添加一个空值合并运算符,将该值默认为 0。
{{signupForm.controls['additionalInformation'].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['additionalInformation'].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['additionalInformation'].value?.length ?? 0}} /{{maxCharsOfArea}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论