简体   繁体   English

如何在angular5中使用split在wordcount中

[英]how to use split in angular5 for wordcount

I am trying to do the wordcount in textarea but it shows after page load Words:1. 我正在尝试在textarea中进行字数统计,但页面加载后会显示Words:1。 whats wrong in this and what i need to do. 这是什么问题,我需要做什么。 can anyone please tell me. 谁能告诉我。

Thanks in advance. 提前致谢。

My component.html 我的component.html

<textarea [(ngModel)]="review.Roman" name="Roman" id='text' required></textarea>
<p>Words:{{value.length}}</p>

My component.ts 我的component.ts

export class PostReviewComponent implements OnInit {
    value: any = {};
    reviews: Reviews[];
    review: Reviews = {
        Roman:''
    };

    ngOnInit() {
        var str = this.review.Roman;
        this.value = str.split(' ');
    }
}

I have few more values in my Reviews array here i am showing only Roman. 我的Reviews数组中没有更多的值,这里我只显示罗马字。

let re = /\s/g

this.value=str.split(re) 

You just need to use RE instead for hardcoded space 您只需要使用RE代替硬编码空间

Let me know if there is any issue 让我知道是否有任何问题

The reason it shows after page load is because of the code you have in your ngOnInit method that gets executed when the page loads. 页面加载后显示的原因是由于ngOnInit方法中包含的代码会在页面加载时执行。

Best way is to use angular pipes and using this way you can re-utilize anywhere in your code. 最好的方法是使用角形管道,并使用这种方式可以在代码中的任何地方重新利用。 Having something like this: 有这样的事情:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'wordsCount'})
export class WordsCountPipe implements PipeTransform {
  transform(value: string): number {
    return value.split(' ').length;
  }
}

And then in your component.html 然后在您的component.html

<textarea [(ngModel)]="review.Roman" name="Roman" id='text' required></textarea>
<p>Words:{{value | wordsCount}}</p>

Note : Remember to register custom pipes in the declaration array. 注意 :请记住在声明数组中注册自定义管道。

EDIT : If you don't want to use pipes you can use (ngModelChange) to update your value property. 编辑 :如果您不想使用管道,则可以使用(ngModelChange)更新您的value属性。

In your component.html 在您的component.html

<textarea [(ngModel)]="review.Roman" (ngModelChange)="valueChanges($event)"></textarea><br>
{{value.length}}

and then in your component.ts add valueChanges method: 然后在您的component.ts添加valueChanges方法:

export class PostReviewComponent implements OnInit {
    value: any = [];
    reviews: Reviews[];
    review: Reviews = {
        Roman:''
    };

    ngOnInit() {
    }

    valueChanges(modelValue: string) {
        this.value = modelValue.split(' ');  
    }
}

Every time your model is updated, it will update the word count. 每次更新模型时,都会更新字数。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM