如何在角度6的键盘输入中计算字符

时间:2018-11-20 05:13:23

标签: angular typescript

您如何计算角度6的keyup事件中的字符,包括空格?

import { Component } from '@angular/core';
@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent { }

4 个答案:

答案 0 :(得分:5)

您可以按以下方式计算字符 box.value.length 要么 box.value?.length

?在属性之后将检查未定义。

答案 1 :(得分:1)

使用2向绑定,您可以绑定到box,它将随着更改而自动更新。您无需在此处使用(keyup)事件处理程序:

template: `
    <input [(ngModel)]="box">
    <p>{{box.length}}</p>
  `    

在您的模块中,从此处导入FormsModule:

import { FormsModule } from '@angular/forms';

这将允许您使用ngModel。 [()]打开2向绑定,这意味着显示和值将自动保持同步,而无需任何额外的逻辑。

答案 2 :(得分:0)

使用{{box.value.length}}

import { Component } from '@angular/core';
@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
    <p>{{box.value.length}}</p>
  `
})
export class LoopbackComponent { }

答案 3 :(得分:0)

您还可以使用以下方法:

import { Component } from '@angular/core';
@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="onKeyUp(box)">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent { 

  onKeyUp(boxInput : HTMLInputElement){
    let length = boxInput.value.length ; //this will have the length of the text entered in the input box
    console.log(length);
  }
}