Split a string from each object inside array

hi guys,
i am new in ionic 2
i want to split a string from each object inside array

i have a array like this:
array = [

{
'name": ''name1",
time: time1,
workToDo: ‘work1 \n work2 \n work3}’ ,

{'name": ''name3",
time: time2,
workToDo: ‘work1 \n work2 \n work3}’ ,

{'name": ''name1",
time: time3,
workToDo: ‘work1 \n work2 \n work3’
}
]

i want to split workToDo value by \n
and want to show this balue in browser

in html:

<div *ngFor="let item of array">
   <p>{{item.name}}</p>
   <p>{{item.time}}</p>
   <div>
      {{ item.workToDo}}
   </div>
</div>

please help me
i want to show {{ item.workToDo }} as a list format like this this attached bellow
Capture

You can do that in many ways but I will mention one way:

make a function:

reformat(str: string) {
  if (str) {
    return str.replace(/\n/g, ',').replace(/\s/g, '').split(',');
  }
return [];
}

isAvailable(item) {

  if (item && item.indexOf('\n') !== -1) {
    return true;
  }
  return false;
}

On the template:

<div *ngIf="isAvailable(item.workToDo)">
<div *ngFor="let n of reformat(item.workToDo)">
{{n}}
</div>
</div>

With all due respect, I’m not a big fan of this way. Angular change detection gets called very frequently. As long as it’s dealing with scalar properties, it can know when things have changed. Any time you introduce a function, all that goes out the window.

So, bottom line: do everything you can to eliminate function calls in template expressions. Offload all of that logic into the controller and make it so that all the template has to do is reference properties. That way you are in control of change detection and performance will improve.

1 Like

I actually agree with you. As I said there are many ways to do that, I would do this if it was for my project:

Write a function:

reformat(str:string){
// do the same but call this in the constructor and apply it to the array elements with property workToDo to refactor it.
}

Then the rest should be the same and you do not need isAvailable function.
Other ways could be like using Pipe.