Angular 2 pipe that transforms JSON object to pretty-printed JSON

前端 未结 4 1644
清酒与你
清酒与你 2020-12-02 15:01

Trying to write an Angular 2 pipe that will take a JSON object string and return it pretty-printed/formatted to display to the user.

For example, it would take this:

4条回答
  •  感情败类
    2020-12-02 15:49

    I would create a custom pipe for this:

    @Pipe({
      name: 'prettyprint'
    })
    export class PrettyPrintPipe implements PipeTransform {
      transform(val) {
        return JSON.stringify(val, null, 2)
          .replace(' ', ' ')
          .replace('\n', '
    '); } }

    and use it this way:

    @Component({
      selector: 'my-app',
      template: `
        
    `, pipes: [ PrettyPrintPipe ] }) export class AppComponent { obj = { test: 'testttt', name: 'nameeee' } }

    See this stackblitz: https://stackblitz.com/edit/angular-prettyprint

提交回复
热议问题