0

I have to show the input characters counter several times in distinct components. So I thought it was best to create a component for it.

Example:

input counter

I have tried to make a template reference variable and show its value. However, the count isn't dynamic. It stays static. Here's the live example in StackBlitz.

The code is very simple:

app.component.html

<input type="text" #input>
<app-caracter-counter [input]="input.value.length"></app-caracter-counter>

And the code of the component I created:

caracter-count.component.ts

export class CaracterCounterComponent implements OnInit {
  @Input() input:number;
}

This was the simplest way I found, but doesn't work.

I tried binding an event emmitter, but that would require to use the @Output in all components that I use this caracter-counter.

Is there any way to make this component works using only template tags (in the component that I'll be using the caracter-counter)?

Bianca Pereira
  • 65
  • 2
  • 10

3 Answers3

1

Great answers has been posted before. Here a little improvement, in case you are using formControlName inside a formGroup in a ReactiveForms scenario than you neither need to use templateAccess variable nor ngModel. Here is a sample code

<form [formGroup]="myFormGroup">
<input type="text" formControlName="txtCtrl1" />
</form>
<app-caracter-counter [input]="myFormGroup.get('txtCtrl1').value.length"></app-caractercounter>

Please find the working StackBlitz.

Thanks.

Obaid
  • 2,563
  • 17
  • 15
0

You should use ngModel to create a two way binding from your input field to a AppComponent property, then pass that property to your child component:

Created a blitzstack for you

In your app.html

<input type="text" [(ngModel)]="text">

<div *ngIf="text.length !== 0">
    <app-caracter-counter [input]="text.length"></app-caracter-counter>
</div>

In your app.ts

export class AppComponent  {
  text: string = '';
}
Ethan Vu
  • 2,911
  • 9
  • 25
  • I cannot add ngModel because an error is trigered: "ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead." and doesn't work – Bianca Pereira Jul 19 '19 at 18:41
  • 1
    `[ngModelOptions]="{standalone: true}"`, add this to your input, you can read more about it here https://stackoverflow.com/questions/39126638/ngmodel-cannot-be-used-to-register-form-controls-with-a-parent-formgroup-directi – Ethan Vu Jul 19 '19 at 18:43
0

Change your code to this

<input type="text" (keyup)="true" (change)="true" #textInput>
<div *ngIf="textInput.value.length !== 0">
 <app-caracter-counter [input]="textInput.value.length"></app-caracter-counter> 
</div>

I added (keyup)="true" (change)="true" and change your condition to textInput.value.length !== 0 (instead of ===)

You don't need to do that when using input with forms since you have ngModel or formControlName

Reza
  • 18,865
  • 13
  • 88
  • 163