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)?

4

3 回答 3

1

之前已经发布了很好的答案。这里有一点改进,如果您在ReactiveForms场景中的formGroup内使用formControlName ,则不需要使用 templateAccess 变量或 ngModel。这是一个示例代码

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

请找到有效的StackBlitz

谢谢。

于 2019-07-19T19:25:08.457 回答
0

将您的代码更改为此

<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>

我添加(keyup)="true" (change)="true"并将您的条件更改为textInput.value.length !== 0(而不是===

将输入与表单一起使用时,您不需要这样做,因为您有ngModelformControlName

于 2019-07-19T18:29:18.210 回答
0

您应该使用ngModel创建从输入字段到 AppComponent 属性的双向绑定,然后将该属性传递给您的子组件:

为您创建了一个闪电战

在你的 app.html

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

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

在你的 app.ts

export class AppComponent  {
  text: string = '';
}
于 2019-07-19T18:24:58.183 回答