118
rated 0 times
[
122]
[
4]
/ answers: 1 / hits: 17328
/ 8 Years ago, wed, october 5, 2016, 12:00:00
I'm using Angular2 reactive forms, and I want to display a character count of a textarea
as the user types.
I was hoping to just be able to include the form control's name.length
in my html like so:
<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>
This works however the length
of the form control lags one keystroke behind. So for example if I type a
into the textarea {{alaynaPage.incidentDescription.length}}
is 0. If i then type b
(so string is ab
) {{alaynaPage.incidentDescription.length}}
is now 1.
How do I get this to work as expected?
I got it to work via a hack but there has to be an easier way:
//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>
More From » angular