我正在使用 Angular2 响应式表单,我想在用户输入时显示 textarea 的字符数。
我希望能够像这样在我的 html 中包含表单控件的 name.length:
<div class="form-group">
<label for="incidentDescription">Brief Description of Incident</label>
<textarea id="incidentDescription" formControlName="incidentDescription" required [attr.maxLength]="maxIncidentDescriptionLength"></textarea>
<small><code>{{alaynaPage.incidentDescription.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
</div>
这“有效”,但是表单控件的 length 滞后一次击键。例如,如果我在文本区域中键入 a,{{alaynaPage.incidentDescription.length}} 为 0。如果我随后键入 b(因此字符串是 ab) {{alaynaPage.incidentDescription.length}} 现在是 1。
如何让它按预期工作?
我通过 hack 让它工作,但必须有更简单的方法:
//in component:
theLength: number = 0;
ngOnInit(): void {
this.buildForm();
(this.alaynaPageForm.controls['incidentDescription'] as FormControl).valueChanges.subscribe(value => {
// do something with value here
this.theLength = value.length;
});
}
//in my html:
<small class="form-text text-muted"><code>{{theLength}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
最佳答案
你只需要使用 template reference variable
<textarea id="incidentDescription" formControlName="incidentDescription" #incidentDescription></textarea>
<small class="form-text text-muted"><code>{{incidentDescription.value.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
关于javascript - Angular 2 : how do display character count on reactive form input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39865189/