program story

JSON 객체를 예쁘게 인쇄 된 JSON으로 변환하는 Angular 2 파이프

inputbox 2020. 10. 20. 07:36
반응형

JSON 객체를 예쁘게 인쇄 된 JSON으로 변환하는 Angular 2 파이프


JSON 개체 문자열을 가져와 사용자에게 표시하기 위해 예쁜 인쇄 / 형식으로 반환하는 Angular 2 파이프를 작성하려고합니다.

예를 들어 다음과 같습니다.

{ "id": 1, "number": "K3483483344", "state": "CA", "active": true}

그리고 HTML로 표시 될 때 다음과 같은 것을 반환합니다.

여기에 이미지 설명 입력

그래서 내 견해로는 다음과 같은 것을 가질 수 있습니다.

<td> {{ record.jsonData | prettyprint }} </td>

내장 json파이프를 사용하여 더 간단한 방법을 추가하고 싶습니다 .

<pre>{{data | json}}</pre>

이렇게하면 서식이 유지됩니다.


이를 위해 사용자 지정 파이프를 만듭니다.

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

다음과 같이 사용하십시오.

@Component({
  selector: 'my-app',
  template: `
    <div [innerHTML]="obj | prettyprint"></div>
  `,
  pipes: [ PrettyPrintPipe ]
})
export class AppComponent {
  obj = {
    test: 'testttt',
    name: 'nameeee'
  }
}

이 stackblitz를 참조하십시오 : https://stackblitz.com/edit/angular-prettyprint

참고 URL : https://stackoverflow.com/questions/37308420/angular-2-pipe-that-transforms-json-object-to-pretty-printed-json

반응형