简体   繁体   中英

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. whats wrong in this and what i need to do. can anyone please tell me.

Thanks in advance.

My component.html

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

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

let re = /\s/g

this.value=str.split(re) 

You just need to use RE instead for hardcoded space

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.

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

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

In your component.html

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

and then in your component.ts add valueChanges method:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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