replace \n with <br> tag angular 6

送分小仙女□ 提交于 2020-08-19 11:14:12

问题


i have rest api whit /n code, can angular 6 replace with <br> tag

here's my code:

{{x.deskripsi}}

i try use https://www.npmjs.com/package/angular-nl2br-filter

but i have no idea how to use with binding inside {{}} tag

i try using this code

<p ng-bind-html="x.deskripsi | nl2br"></p>

but doesn't work

any help?

thanks before


回答1:


You don't need a library. Simply set the white-space property of your tag to pre-wrap (or use a <pre> tag that should have this style by default)

document.querySelector('#formatted').innerText = 'Lorem\nIpsum';
#formatted {
  white-space: pre-wrap;
}
<div id="formatted"></div>
<div>Lorem\nIpsum</div>



回答2:


You can use a pipe for the same:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replaceLineBreaks'})
export class ReplaceLineBreaks implements PipeTransform {
transform(value: string): string {
      return value.replace(/\n/g, '<br/>');
   }
}

The pipe must be included in your @NgModule declarations to be included in the app. To show the HTML in your template you can use binding innerHTML.

<p [innerHTML]="x.deskripsi | replaceLineBreaks"></p>


来源:https://stackoverflow.com/questions/50327396/replace-n-with-br-tag-angular-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!