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>
You just need to use a 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>
You want a hack, here's the hack. Use this:
{{alaynaPageForm.value?.incidentDescription?.length}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With