dedicated pipe for truncating

This commit is contained in:
Evert Prants 2020-11-08 17:49:23 +02:00
parent 66216075e7
commit f977ffd65d
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
5 changed files with 25 additions and 11 deletions

View File

@ -11,6 +11,7 @@ import { GenderPipe } from './gender.pipe';
import { ListPaginateComponent } from './list-paginate/list-paginate.component'; import { ListPaginateComponent } from './list-paginate/list-paginate.component';
import { ListService } from './list.service'; import { ListService } from './list.service';
import { ListComponent } from './list/list.component'; import { ListComponent } from './list/list.component';
import { TruncatePipe } from './truncate.pipe';
@NgModule({ @NgModule({
bootstrap: [AppComponent], bootstrap: [AppComponent],
@ -21,6 +22,7 @@ import { ListComponent } from './list/list.component';
ListPaginateComponent, ListPaginateComponent,
GenderPipe, GenderPipe,
CustomSortPipe, CustomSortPipe,
TruncatePipe,
], ],
imports: [ imports: [
BrowserModule, BrowserModule,

View File

@ -69,7 +69,7 @@
</div> </div>
</div> </div>
<div class="detail"> <div class="detail">
<p>{{ getPersonDetail(person) }}</p> <p>{{ person.intro | truncate:300:true }}</p>
</div> </div>
</div> </div>
</td> </td>

View File

@ -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 { private getList(): void {
this.listService.getList().subscribe( this.listService.getList().subscribe(
(data) => { (data) => {

View File

@ -0,0 +1,8 @@
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe', () => {
it('create an instance', () => {
const pipe = new TruncatePipe();
expect(pipe).toBeTruthy();
});
});

14
src/app/truncate.pipe.ts Normal file
View File

@ -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;
}
}