Search code examples
jsonangularangular-materialdialogstringify

Angular Material Dialog & JSON.stringify


I am unable to show the string provided by JSON.stringify including the spaces for indentation inside a material dialog of my Angular project. It always appears as a raw data string, without any spacing for the indentation, even if I use the spaces parameter. The funny thing is that the same code provides a good indentation if I console.log it.

component.ts :

[...]
onClickJSON() {
    let dialogConfig = new MatDialogConfig()
    dialogConfig.data = {
        json: this.item
    }
this.jsonDialog.open(JsonDialogComponent, dialogConfig)
[...]

dialog.ts :

[...]
export class JsonDialogComponent implements OnInit {

    json: string;

    constructor(private dialogRef: MatDialogRef<JsonDialogComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any) {
    console.log(JSON.stringify(this.data['json'], null, 4)) //Good appearance
    this.json = JSON.stringify(this.data['json'], null, 4) //Bad appearance, like raw data
[...]

dialog.html :

<p>
    {{json}}
</p>

Solution

  • That's because you didn't use the correct tag.

    Instead of using <p>, use either

    <pre>{{ json }}</pre>
    

    or

    <pre><code>{{ json }}<code></pre>
    

    More in depth, this is due to CSS styling, you can check the native styling of the pre tag and apply it to your p if you want. But semantically speaking, it's better to use <pre> than <p> in that case.