Reputation: 948
I am receiving data from REST api. For name parameter, I want to split it at 2330 and give new line break.
Example: I have name: ABCD 2330 This is My Name
I want to give different style to the split strings and the output on my screen to be:
ABCD 2330
This is My Name // this will be bold
and not
ABCD 2330 This is My Name
Given the complexity of my object, I don't think I can put this operation in the ts file. I am binding the data like: <li>{{data.name}}</li>
can I use some pipe like split and how would I add /n after the split and rejoin the string and also how can I give different style in the same
Upvotes: 4
Views: 12956
Reputation: 2582
For a simple use case it might not be necessary to add a pipe.
I've done the following
In .ts
myName;
// data received
handleData(data) {
var originalName = data.name;
this.myName = originalName.split("name")[0]
}
In the .html
{{myName}}
Upvotes: 1
Reputation: 5041
Maybe you can try like below
Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'texttransform'})
export class TextTransformPipe implements PipeTransform {
transform(value: string): string {
const splitBy = '2330'
const splittedText = value.split( splitBy );
return `${ splittedText[0] } ${ splitBy } <br> <b>${ splittedText[1] }</b>`;
}
}
And in the template file
<ul>
<li *ngFor="let data of receivedData" [innerHTML]="data.name | texttransform"></li>
</ul>
Working stackblitz
Upvotes: 2
Reputation: 1486
Hey you just have to make custom pipe and use that pipe in your html to format the string as per your requirement.
To make the custom pipe use the following lines of code:
@Pipe({ name: 'myPipe' })
export class MyPipe implements PipeTransform {
transform(value: any) {
if (value) {
let firstLine= value.substr(0,9);
let secondLine= value.substr(9).bold();
return firstLine+'/n'+secondLine
}
return value;
}
}
Upvotes: 0