Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: how do display character count on reactive form input

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>
like image 564
rynop Avatar asked Oct 05 '16 03:10

rynop


2 Answers

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>
like image 120
rynop Avatar answered Sep 21 '22 13:09

rynop


You want a hack, here's the hack. Use this:

{{alaynaPageForm.value?.incidentDescription?.length}}
like image 26
Harry Ninh Avatar answered Sep 21 '22 13:09

Harry Ninh