Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
1

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>

[#60501] Sunday, October 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;