Programing

Angular2에서 텍스트를 자르는 방법은 무엇입니까?

lottogame 2020. 8. 27. 08:06
반응형

Angular2에서 텍스트를 자르는 방법은 무엇입니까?


문자열 길이를 숫자로 제한 할 수있는 방법이 있습니까? 예 : 제목 길이를 20으로 제한해야합니다 {{ data.title }}.

길이를 제한하는 파이프 나 필터가 있습니까?


텍스트를 각도로 자르는 두 가지 방법.

let str = 'How to truncate text in angular';

1. 솔루션

  {{str | slice:0:6}}

산출:

   how to

슬라이스 문자열 뒤에 텍스트를 추가하려면

   {{ (str.length>6)? (str | slice:0:6)+'..':(str) }}

산출:

 how to...

2. 솔루션 (커스텀 파이프 생성)

사용자 지정 절단 파이프를 생성하려는 경우

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

@Pipe({
 name: 'truncate'
})

export class TruncatePipe implements PipeTransform {

transform(value: string, args: string[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

마크 업에서

{{ str | truncate:[20] }} // or 
{{ str | truncate:[20, '...'] }} // or

모듈 항목을 추가하는 것을 잊지 마십시오.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

선택적 매개 변수로 파이프 자르기 :

  • 제한 -문자열 최대 길이
  • completeWords- 문자 대신 가장 가까운 완전한 단어에서자를 플래그
  • 줄임표 -추가 된 후행 접미사

-

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

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
    if (completeWords) {
      limit = value.substr(0, limit).lastIndexOf(' ');
    }
    return `${value.substr(0, limit)}${ellipsis}`;
  }
}

모듈 항목을 추가하는 것을 잊지 마십시오.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

용법

예제 문자열 :

public longStr = 'A really long string that needs to be truncated';

마크 업 :

  <h1>{{longStr | truncate }}</h1> 
  <!-- Outputs: A really long string that... -->

  <h1>{{longStr | truncate : 12 }}</h1> 
  <!-- Outputs: A really lon... -->

  <h1>{{longStr | truncate : 12 : true }}</h1> 
  <!-- Outputs: A really... -->

  <h1>{{longStr | truncate : 12 : false : '***' }}</h1> 
  <!-- Outputs: A really lon*** -->

You can truncate text based on css. its help to truncate a text based on width not fix character.

Example

CSS

.truncate {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

content {
            width:100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

HTML

<div class="content">
    <span class="truncate">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
</div>

Note: this code use full for one line.

Ketan's Solution is best if you want to do it by Angular


I've been using this module ng2 truncate, its pretty easy, import module and u are ready to go... in {{ data.title | truncate : 20 }}


If you want to truncate by a number of words and add an ellipsis you can use this function:

truncate(value: string, limit: number = 40, trail: String = '…'): string {
  let result = value || '';

  if (value) {
    const words = value.split(/\s+/);
    if (words.length > Math.abs(limit)) {
      if (limit < 0) {
        limit *= -1;
        result = trail + words.slice(words.length - limit, words.length).join(' ');
      } else {
        result = words.slice(0, limit).join(' ') + trail;
      }
    }
  }

  return result;
}

Example:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 5, '…')
> "Bacon ipsum dolor amet sirloin…"

taken from: https://github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts

If you want to truncate by a number of letters but don't cut words out use this:

truncate(value: string, limit = 25, completeWords = true, ellipsis = '…') {
  let lastindex = limit;
  if (completeWords) {
    lastindex = value.substr(0, limit).lastIndexOf(' ');
  }
  return `${value.substr(0, limit)}${ellipsis}`;
}

Example:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, true, '…')
> "Bacon ipsum dolor…"

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, false, '…')
> "Bacon ipsum dolor a…"

Just tried @Timothy Perez answer and added a line

if (value.length < limit)
   return `${value.substr(0, limit)}`;

to

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

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {

   if (value.length < limit)
   return `${value.substr(0, limit)}`;

   if (completeWords) {
     limit = value.substr(0, limit).lastIndexOf(' ');
   }
   return `${value.substr(0, limit)}${ellipsis}`;
}
}

참고URL : https://stackoverflow.com/questions/44669340/how-to-truncate-text-in-angular2

반응형