我正在使用Angular2反應形式,並且我想在用戶鍵入時顯示textarea
的字符計數。Angular2:如何顯示反應形式輸入字符計數
我希望只能夠包含表單控件的name.length
在我的HTML像這樣:
<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
到textarea的{{alaynaPage.incidentDescription.length}}
爲0。如果我再鍵入b
(因此字符串ab
){{alaynaPage.incidentDescription.length}}
現在是1
我如何得到這個達到預期效果?
我得到了它的通過破解工作,但必須有一個更簡單的方法:
//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>
讓人驚訝 - 這是一個黑客。我只是想清楚如何幹淨地做。看我的答案 – rynop