在textarea Angular 5中键入时显示字符数

时间:2018-09-21 05:45:26

标签: angular5 charactercount

我正在尝试编写代码以显示textarea字段下方的字符数。我找到了许多解决方案,但我不知道为什么它不适合我。

这是我正在尝试的代码:

<div class="form-group border-0 describe mb-0">
  <label for="describewishInput" i18n="@@describewishLabel" class="text-capitalize">Describe Your Wish:</label>
    <span ngbTooltip="Please describe your wish here"
            placement="top" class="tt tt-bottom mt-1 mr-0"></span>
      <textarea type="text" (ngModel)="yourWish" id="yourWish" class="form-control mb-1" maxlength="255" i18n-placeholder="@@describeyourwish"></textarea>
      <span class="pull-right char"><em>{{ 255 - yourWish.length }} characters left</em></span>
</div>

这是我遇到的错误

SignupFormComponent.html:121 ERROR TypeError: Cannot read property 'length' of undefined
at Object.eval [as updateRenderer] (SignupFormComponent.html:122)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
at checkAndUpdateView (core.js:13849)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
at callViewAction (core.js:14195)

您能帮我吗?我从1天开始研究它就非常沮丧。

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要使用两种方式的数据绑定 [(ngModel)]

<textarea type="text" [(ngModel)]="yourWish" id="yourWish" class="form-control mb-1" maxlength="255" i18n-placeholder="@@describeyourwish"></textarea>

STACKBLITZ DEMO