diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 0b65511..e9adb78 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -11,6 +11,7 @@ import { GenderPipe } from './gender.pipe'; import { ListPaginateComponent } from './list-paginate/list-paginate.component'; import { ListService } from './list.service'; import { ListComponent } from './list/list.component'; +import { TruncatePipe } from './truncate.pipe'; @NgModule({ bootstrap: [AppComponent], @@ -21,6 +22,7 @@ import { ListComponent } from './list/list.component'; ListPaginateComponent, GenderPipe, CustomSortPipe, + TruncatePipe, ], imports: [ BrowserModule, diff --git a/src/app/list/list.component.html b/src/app/list/list.component.html index de16405..5478b28 100644 --- a/src/app/list/list.component.html +++ b/src/app/list/list.component.html @@ -69,7 +69,7 @@
-

{{ getPersonDetail(person) }}

+

{{ person.intro | truncate:300:true }}

diff --git a/src/app/list/list.component.ts b/src/app/list/list.component.ts index 2d574ce..6816037 100644 --- a/src/app/list/list.component.ts +++ b/src/app/list/list.component.ts @@ -67,16 +67,6 @@ export class ListComponent implements OnInit { } } - public getPersonDetail(person: IPerson): string { - const str = person.intro.replace(/<.*?>/g, ''); - let words = str.split(' '); - if (words.length >= 38) { - words = words.slice(0, 37); - words[words.length - 1] += '...'; - } - return words.join(' '); - } - private getList(): void { this.listService.getList().subscribe( (data) => { diff --git a/src/app/truncate.pipe.spec.ts b/src/app/truncate.pipe.spec.ts new file mode 100644 index 0000000..b16f3ef --- /dev/null +++ b/src/app/truncate.pipe.spec.ts @@ -0,0 +1,8 @@ +import { TruncatePipe } from './truncate.pipe'; + +describe('TruncatePipe', () => { + it('create an instance', () => { + const pipe = new TruncatePipe(); + expect(pipe).toBeTruthy(); + }); +}); diff --git a/src/app/truncate.pipe.ts b/src/app/truncate.pipe.ts new file mode 100644 index 0000000..fe3f7ba --- /dev/null +++ b/src/app/truncate.pipe.ts @@ -0,0 +1,14 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ + name: 'truncate', +}) +export class TruncatePipe implements PipeTransform { + public transform(value: string, limit = 10, words = false, ellipsis = '...'): string { + value = value.replace(/<.*?>/g, ''); + if (words) { + limit = value.substr(0, limit).lastIndexOf(' '); + } + return value.length > limit ? value.substr(0, limit) + ellipsis : value; + } +}